idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
239,200 | def get_redis_connection ( ) : if config . MOCK_REDIS : import mockredis return mockredis . mock_strict_redis_client ( ) elif config . DEFENDER_REDIS_NAME : try : cache = caches [ config . DEFENDER_REDIS_NAME ] except InvalidCacheBackendError : raise KeyError ( INVALID_CACHE_ERROR_MSG . format ( config . DEFENDER_REDIS... | Get the redis connection if not using mock |
239,201 | def parse_redis_url ( url ) : redis_config = { "DB" : 0 , "PASSWORD" : None , "HOST" : "localhost" , "PORT" : 6379 , "SSL" : False } if not url : return redis_config url = urlparse . urlparse ( url ) path = url . path [ 1 : ] path = path . split ( '?' , 2 ) [ 0 ] if path : redis_config . update ( { "DB" : int ( path ) ... | Parses a redis URL . |
239,202 | def handle ( self , ** options ) : print ( "Starting clean up of django-defender table" ) now = timezone . now ( ) cleanup_delta = timedelta ( hours = config . ACCESS_ATTEMPT_EXPIRATION ) min_attempt_time = now - cleanup_delta attempts_to_clean = AccessAttempt . objects . filter ( attempt_time__lt = min_attempt_time , ... | Removes any entries in the AccessAttempt that are older than your DEFENDER_ACCESS_ATTEMPT_EXPIRATION config default 24 HOURS . |
239,203 | def connection ( self , shareable = True ) : if shareable and self . _maxshared : self . _lock . acquire ( ) try : while ( not self . _shared_cache and self . _maxconnections and self . _connections >= self . _maxconnections ) : self . _wait_lock ( ) if len ( self . _shared_cache ) < self . _maxshared : try : con = sel... | Get a steady cached DB - API 2 connection from the pool . |
239,204 | def unshare ( self , con ) : self . _lock . acquire ( ) try : con . unshare ( ) shared = con . shared if not shared : try : self . _shared_cache . remove ( con ) except ValueError : pass finally : self . _lock . release ( ) if not shared : self . cache ( con . con ) | Decrease the share of a connection in the shared cache . |
239,205 | def close ( self ) : if self . _con : self . _pool . unshare ( self . _shared_con ) self . _shared_con = self . _con = None | Close the pooled shared connection . |
239,206 | def steady_connection ( self ) : return connect ( self . _creator , self . _maxusage , self . _setsession , self . _failures , self . _ping , self . _closeable , * self . _args , ** self . _kwargs ) | Get a steady non - persistent DB - API 2 connection . |
239,207 | def connection ( self , shareable = False ) : try : con = self . thread . connection except AttributeError : con = self . steady_connection ( ) if not con . threadsafety ( ) : raise NotSupportedError ( "Database module is not thread-safe." ) self . thread . connection = con con . _ping_check ( ) return con | Get a steady persistent DB - API 2 connection . |
239,208 | def steady_connection ( self ) : return SteadyPgConnection ( self . _maxusage , self . _setsession , self . _closeable , * self . _args , ** self . _kwargs ) | Get a steady non - persistent PyGreSQL connection . |
239,209 | def connection ( self ) : try : con = self . thread . connection except AttributeError : con = self . steady_connection ( ) self . thread . connection = con return con | Get a steady persistent PyGreSQL connection . |
239,210 | def versionString ( version ) : ver = list ( map ( str , version ) ) numbers , rest = ver [ : 2 if ver [ 2 ] == '0' else 3 ] , ver [ 3 : ] return '.' . join ( numbers ) + '-' . join ( rest ) | Create version string . |
239,211 | def steady_connection ( self ) : return SteadyPgConnection ( self . _maxusage , self . _setsession , True , * self . _args , ** self . _kwargs ) | Get a steady unpooled PostgreSQL connection . |
239,212 | def connection ( self ) : if self . _connections : if not self . _connections . acquire ( self . _blocking ) : raise TooManyConnections try : con = self . _cache . get ( 0 ) except Empty : con = self . steady_connection ( ) return PooledPgConnection ( self , con ) | Get a steady cached PostgreSQL connection from the pool . |
239,213 | def cache ( self , con ) : try : if self . _reset == 2 : con . reset ( ) else : if self . _reset or con . _transaction : try : con . rollback ( ) except Exception : pass self . _cache . put ( con , 0 ) except Full : con . close ( ) if self . _connections : self . _connections . release ( ) | Put a connection back into the pool cache . |
239,214 | def reopen ( self ) : if self . _con : self . _con . reopen ( ) else : self . _con = self . _pool . connection ( ) | Reopen the pooled connection . |
239,215 | def reopen ( self ) : try : self . _con . reopen ( ) except Exception : if self . _transcation : self . _transaction = False try : self . _con . query ( 'rollback' ) except Exception : pass else : self . _transaction = False self . _closed = False self . _setsession ( ) self . _usage = 0 | Reopen the tough connection . |
239,216 | def reset ( self ) : try : self . _con . reset ( ) self . _transaction = False self . _setsession ( ) self . _usage = 0 except Exception : try : self . reopen ( ) except Exception : try : self . rollback ( ) except Exception : pass | Reset the tough connection . |
239,217 | def _get_tough_method ( self , method ) : def tough_method ( * args , ** kwargs ) : transaction = self . _transaction if not transaction : try : if not self . _con . db . status : raise AttributeError if self . _maxusage : if self . _usage >= self . _maxusage : raise AttributeError except Exception : self . reset ( ) t... | Return a tough version of a connection class method . |
239,218 | def connect ( creator , maxusage = None , setsession = None , failures = None , ping = 1 , closeable = True , * args , ** kwargs ) : return SteadyDBConnection ( creator , maxusage , setsession , failures , ping , closeable , * args , ** kwargs ) | A tough version of the connection constructor of a DB - API 2 module . |
239,219 | def _create ( self ) : con = self . _creator ( * self . _args , ** self . _kwargs ) try : try : if self . _dbapi . connect != self . _creator : raise AttributeError except AttributeError : try : mod = con . __module__ except AttributeError : mod = None while mod : try : self . _dbapi = sys . modules [ mod ] if not call... | Create a new connection using the creator function . |
239,220 | def _store ( self , con ) : self . _con = con self . _transaction = False self . _closed = False self . _usage = 0 | Store a database connection for subsequent use . |
239,221 | def _reset ( self , force = False ) : if not self . _closed and ( force or self . _transaction ) : try : self . rollback ( ) except Exception : pass | Reset a tough connection . |
239,222 | def begin ( self , * args , ** kwargs ) : self . _transaction = True try : begin = self . _con . begin except AttributeError : pass else : begin ( * args , ** kwargs ) | Indicate the beginning of a transaction . |
239,223 | def commit ( self ) : self . _transaction = False try : self . _con . commit ( ) except self . _failures as error : try : con = self . _create ( ) except Exception : pass else : self . _close ( ) self . _store ( con ) raise error | Commit any pending transaction . |
239,224 | def cancel ( self ) : self . _transaction = False try : cancel = self . _con . cancel except AttributeError : pass else : cancel ( ) | Cancel a long - running transaction . |
239,225 | def _setsizes ( self , cursor = None ) : if cursor is None : cursor = self . _cursor if self . _inputsizes : cursor . setinputsizes ( self . _inputsizes ) for column , size in self . _outputsizes . items ( ) : if column is None : cursor . setoutputsize ( size ) else : cursor . setoutputsize ( size , column ) | Set stored input and output sizes for cursor execution . |
239,226 | def close ( self ) : if not self . _closed : try : self . _cursor . close ( ) except Exception : pass self . _closed = True | Close the tough cursor . |
239,227 | def _get_tough_method ( self , name ) : def tough_method ( * args , ** kwargs ) : execute = name . startswith ( 'execute' ) con = self . _con transaction = con . _transaction if not transaction : con . _ping_check ( 4 ) try : if con . _maxusage : if con . _usage >= con . _maxusage : raise con . _failure if execute : se... | Return a tough version of the given cursor method . |
239,228 | def train_punkt ( ctx , input , output , abbr , colloc ) : click . echo ( 'chemdataextractor.tokenize.train_punkt' ) import pickle from nltk . tokenize . punkt import PunktSentenceTokenizer , PunktTrainer punkt = PunktTrainer ( ) for fin in input : click . echo ( 'Training on %s' % fin . name ) sentences = fin . read (... | Train Punkt sentence splitter using sentences in input . |
239,229 | def sentences ( ctx , input , output ) : log . info ( 'chemdataextractor.read.elements' ) log . info ( 'Reading %s' % input . name ) doc = Document . from_file ( input ) for element in doc . elements : if isinstance ( element , Text ) : for raw_sentence in element . raw_sentences : output . write ( raw_sentence . strip... | Read input document and output sentences . |
239,230 | def words ( ctx , input , output ) : log . info ( 'chemdataextractor.read.elements' ) log . info ( 'Reading %s' % input . name ) doc = Document . from_file ( input ) for element in doc . elements : if isinstance ( element , Text ) : for sentence in element . sentences : output . write ( u' ' . join ( sentence . raw_tok... | Read input document and output words . |
239,231 | def _in_stoplist ( self , entity ) : start = 0 end = len ( entity ) for prefix in IGNORE_PREFIX : if entity . startswith ( prefix ) : start += len ( prefix ) break for suffix in IGNORE_SUFFIX : if entity . endswith ( suffix ) : end -= len ( suffix ) break if start >= end : return True entity = entity [ start : end ] if... | Return True if the entity is in the stoplist . |
239,232 | def _process_name ( name ) : name = unescape ( name ) name = NG_RE . sub ( '' , name ) . strip ( ) name = END_RE . sub ( '' , name ) . strip ( ', ' ) name = RATIO_RE . sub ( '' , name ) . strip ( ', ' ) name = START_RE . sub ( '' , name ) . strip ( ) name = BRACKET_RE . sub ( '\g<1>' , name ) comps = name . split ( ', ... | Fix issues with Jochem names . |
239,233 | def _get_variants ( name ) : names = [ name ] oldname = name if DOT_GREEK_RE . search ( name ) : wordname = name while True : m = DOT_GREEK_RE . search ( wordname ) if m : wordname = wordname [ : m . start ( 1 ) - 1 ] + m . group ( 1 ) + wordname [ m . end ( 1 ) + 1 : ] else : break symbolname = name while True : m = D... | Return variants of chemical name . |
239,234 | def prepare_jochem ( ctx , jochem , output , csoutput ) : click . echo ( 'chemdataextractor.dict.prepare_jochem' ) for i , line in enumerate ( jochem ) : print ( 'JC%s' % i ) if line . startswith ( 'TM ' ) : if line . endswith ( ' @match=ci\n' ) : for tokens in _make_tokens ( line [ 3 : - 11 ] ) : output . write ( ' ' ... | Process and filter jochem file to produce list of names for dictionary . |
239,235 | def prepare_include ( ctx , include , output ) : click . echo ( 'chemdataextractor.dict.prepare_include' ) for i , line in enumerate ( include ) : print ( 'IN%s' % i ) for tokens in _make_tokens ( line . strip ( ) ) : output . write ( u' ' . join ( tokens ) ) output . write ( u'\n' ) | Process and filter include file to produce list of names for dictionary . |
239,236 | def build ( ctx , inputs , output , cs ) : click . echo ( 'chemdataextractor.dict.build' ) dt = DictionaryTagger ( lexicon = ChemLexicon ( ) , case_sensitive = cs ) names = [ ] for input in inputs : for line in input : tokens = line . split ( ) names . append ( tokens ) dt . build ( words = names ) dt . save ( output ) | Build chemical name dictionary . |
239,237 | def _parse_table_footnotes ( self , fns , refs , specials ) : footnotes = [ ] for fn in fns : footnote = self . _parse_text ( fn , refs = refs , specials = specials , element_cls = Footnote ) [ 0 ] footnote += Footnote ( '' , id = fn . getprevious ( ) . get ( 'id' ) ) footnotes . append ( footnote ) return footnotes | Override to account for awkward RSC table footnotes . |
239,238 | def extract ( ) : Paragraph . parsers = [ CompoundParser ( ) , ChemicalLabelParser ( ) , MpParser ( ) ] Table . parsers = [ ] patents = [ ] for root , dirs , files in os . walk ( '../examples/mp/grants' ) : for filename in files : if not filename . endswith ( '.xml' ) : continue path = os . path . abspath ( os . path .... | Extract melting points from patents . |
239,239 | def make_sdf ( ) : with open ( '../examples/mp/sdf/chemdataextractor-melting-points.sdf' , 'rb' ) as f_in , gzip . open ( '../examples/mp/sdf/chemdataextractor-melting-points.sdf.gz' , 'wb' ) as f_out : shutil . copyfileobj ( f_in , f_out ) with open ( '../examples/mp/sdf/chemdataextractor-melting-points-filtered.sdf' ... | Produce SDF of ChemDataExtractor and Tetko sample melting points . |
239,240 | def cli ( ctx , verbose ) : log . debug ( 'ChemDataExtractor v%s' % __version__ ) logging . basicConfig ( level = logging . DEBUG if verbose else logging . INFO ) logging . getLogger ( 'requests' ) . setLevel ( logging . WARN ) ctx . obj = { } | ChemDataExtractor command line interface . |
239,241 | def extract ( ctx , input , output ) : log . info ( 'chemdataextractor.extract' ) log . info ( 'Reading %s' % input . name ) doc = Document . from_file ( input , fname = input . name ) records = [ record . serialize ( primitive = True ) for record in doc . records ] jsonstring = json . dumps ( records , indent = 2 , en... | Run ChemDataExtractor on a document . |
239,242 | def read ( ctx , input , output ) : log . info ( 'chemdataextractor.read' ) log . info ( 'Reading %s' % input . name ) doc = Document . from_file ( input ) for element in doc . elements : output . write ( u'%s : %s\n=====\n' % ( element . __class__ . __name__ , six . text_type ( element ) ) ) | Output processed document elements . |
239,243 | def extract_smiles ( s ) : smiles = [ ] for t in s . split ( ) : if len ( t ) > 2 and SMILES_RE . match ( t ) and not t . endswith ( '.' ) and bracket_level ( t ) == 0 : smiles . append ( t ) return smiles | Return a list of SMILES identifiers extracted from the string . |
239,244 | def could_be ( self , other ) : if type ( other ) is not type ( self ) : return NotImplemented if self == other : return True for attr in [ 'title' , 'firstname' , 'middlename' , 'nickname' , 'prefix' , 'lastname' , 'suffix' ] : if attr not in self or attr not in other : continue puncmap = dict ( ( ord ( char ) , None ... | Return True if the other PersonName is not explicitly inconsistent . |
239,245 | def _is_suffix ( self , t ) : return t not in NOT_SUFFIX and ( t . replace ( '.' , '' ) in SUFFIXES or t . replace ( '.' , '' ) in SUFFIXES_LOWER ) | Return true if t is a suffix . |
239,246 | def _tokenize ( self , comps ) : ps = [ ] for comp in comps : ps . extend ( [ c . strip ( ' ,' ) for c in re . split ( r'\s+(?=[^{}]*(?:\{|$))' , comp ) ] ) return [ p for p in ps if p ] | Split name on spaces unless inside curly brackets or quotes . |
239,247 | def _clean ( self , t , capitalize = None ) : if self . _from_bibtex : t = latex_to_unicode ( t , capitalize = capitalize ) t = ' ' . join ( [ el . rstrip ( '.' ) if el . count ( '.' ) == 1 else el for el in t . split ( ) ] ) return t | Convert to normalized unicode and strip trailing full stops . |
239,248 | def _strip ( self , tokens , criteria , prop , rev = False ) : num = len ( tokens ) res = [ ] for i , token in enumerate ( reversed ( tokens ) if rev else tokens ) : if criteria ( token ) and num > i + 1 : res . insert ( 0 , tokens . pop ( ) ) if rev else res . append ( tokens . pop ( 0 ) ) else : break if res : self [... | Strip off contiguous tokens from the start or end of the list that meet the criteria . |
239,249 | def _parse_text ( self , el , refs = None , specials = None , element_cls = Paragraph ) : if specials is None : specials = { } if refs is None : refs = { } elements = self . _parse_element_r ( el , specials = specials , refs = refs , element_cls = element_cls ) if not elements : return [ element_cls ( '' ) ] element = ... | Like _parse_element but ensure a single element . |
239,250 | def _parse_reference ( self , el ) : if '#' in el . get ( 'href' , '' ) : return [ el . get ( 'href' ) . split ( '#' , 1 ) [ 1 ] ] elif 'rid' in el . attrib : return [ el . attrib [ 'rid' ] ] elif 'idref' in el . attrib : return [ el . attrib [ 'idref' ] ] else : return [ '' . join ( el . itertext ( ) ) . strip ( ) ] | Return reference ID from href or text content . |
239,251 | def _is_inline ( self , element ) : if element . tag not in { etree . Comment , etree . ProcessingInstruction } and element . tag . lower ( ) in self . inline_elements : return True return False | Return True if an element is inline . |
239,252 | def _next_token ( self , skipws = True ) : self . _token = next ( self . _tokens ) . group ( 0 ) return self . _next_token ( ) if skipws and self . _token . isspace ( ) else self . _token | Increment _token to the next token and return it . |
239,253 | def _parse_entry ( self ) : entry_type = self . _next_token ( ) . lower ( ) if entry_type == 'string' : self . _parse_string ( ) elif entry_type not in [ 'comment' , 'preamble' ] : self . _parse_record ( entry_type ) | Parse an entry . |
239,254 | def _parse_string ( self ) : if self . _next_token ( ) in [ '{' , '(' ] : field = self . _parse_field ( ) if field : self . definitions [ field [ 0 ] ] = field [ 1 ] | Parse a string entry and store the definition . |
239,255 | def _parse_record ( self , record_type ) : if self . _next_token ( ) in [ '{' , '(' ] : key = self . _next_token ( ) self . records [ key ] = { u'id' : key , u'type' : record_type . lower ( ) } if self . _next_token ( ) == ',' : while True : field = self . _parse_field ( ) if field : k , v = field [ 0 ] , field [ 1 ] i... | Parse a record . |
239,256 | def _parse_field ( self ) : name = self . _next_token ( ) if self . _next_token ( ) == '=' : value = self . _parse_value ( ) return name , value | Parse a Field . |
239,257 | def _parse_value ( self ) : val = [ ] while True : t = self . _next_token ( ) if t == '"' : brac_counter = 0 while True : t = self . _next_token ( skipws = False ) if t == '{' : brac_counter += 1 if t == '}' : brac_counter -= 1 if t == '"' and brac_counter <= 0 : break else : val . append ( t ) elif t == '{' : brac_cou... | Parse a value . Digits definitions and the contents of double quotes or curly brackets . |
239,258 | def parse_names ( cls , names ) : names = [ latex_to_unicode ( n ) for n in re . split ( r'\sand\s(?=[^{}]*(?:\{|$))' , names ) if n ] return names | Parse a string of names separated by and like in a BibTeX authors field . |
239,259 | def metadata ( self ) : auto = { u'records' : self . size } auto . update ( self . meta ) return auto | Return metadata for the parsed collection of records . |
239,260 | def json ( self ) : return json . dumps ( OrderedDict ( [ ( 'metadata' , self . metadata ) , ( 'records' , self . records . values ( ) ) ] ) ) | Return a list of records as a JSON string . Follows the BibJSON convention . |
239,261 | def _flush ( self ) : d = os . path . dirname ( self . path ) if not os . path . isdir ( d ) : os . makedirs ( d ) with io . open ( self . path , 'w' , encoding = 'utf8' ) as f : yaml . safe_dump ( self . _data , f , default_flow_style = False , encoding = None ) | Save the contents of data to the file on disk . You should not need to call this manually . |
239,262 | def _is_allowed_abbr ( self , tokens ) : if len ( tokens ) <= 2 : abbr_text = '' . join ( tokens ) if self . abbr_min <= len ( abbr_text ) <= self . abbr_max and bracket_level ( abbr_text ) == 0 : if abbr_text [ 0 ] . isalnum ( ) and any ( c . isalpha ( ) for c in abbr_text ) : if re . match ( '^\d+(\.\d+)?(g|m[lL]|cm)... | Return True if text is an allowed abbreviation . |
239,263 | def name ( self ) : return '' . join ( '_%s' % c if c . isupper ( ) else c for c in self . __class__ . __name__ ) . strip ( '_' ) . lower ( ) | A unique name for this scraper . |
239,264 | def _post_scrape ( self , value , processor = None ) : value = [ self . process ( v ) for v in value ] value = [ v for v in value if v is not None ] if processor : value = [ processor ( v ) for v in value ] value = [ v for v in value if v is not None ] if not self . all : value = value [ 0 ] if value else None log . de... | Apply processing to the scraped value . |
239,265 | def scrape ( cls , selector , root , xpath = False ) : log . debug ( 'Called scrape classmethod with root: %s' % root ) roots = selector . xpath ( root ) if xpath else selector . css ( root ) results = [ cls ( r ) for r in roots ] return EntityList ( * results ) | Return EntityList for the given selector . |
239,266 | def serialize ( self ) : data = { } for field_name in self : value = self . _values . get ( field_name ) field = self . fields . get ( field_name ) if value is not None : if field . all : value = [ field . serialize ( v ) for v in value ] else : value = field . serialize ( value ) if not field . null and ( ( field . al... | Convert Entity to python dictionary . |
239,267 | def to_json ( self , * args , ** kwargs ) : return json . dumps ( self . serialize ( ) , * args , ** kwargs ) | Convert Entity to JSON . |
239,268 | def from_file ( cls , f , fname = None , readers = None ) : if isinstance ( f , six . string_types ) : f = io . open ( f , 'rb' ) if not fname and hasattr ( f , 'name' ) : fname = f . name return cls . from_string ( f . read ( ) , fname = fname , readers = readers ) | Create a Document from a file . |
239,269 | def from_string ( cls , fstring , fname = None , readers = None ) : if readers is None : from . . reader import DEFAULT_READERS readers = DEFAULT_READERS if isinstance ( fstring , six . text_type ) : raise ReaderError ( 'from_string expects a byte string, not a unicode string' ) for reader in readers : if not reader . ... | Create a Document from a byte string containing the contents of a file . |
239,270 | def get_element_with_id ( self , id ) : return next ( ( el for el in self . elements if el . id == id ) , None ) | Return the element with the specified ID . |
239,271 | def serialize ( self ) : elements = [ ] for element in self . elements : elements . append ( element . serialize ( ) ) data = { 'type' : 'document' , 'elements' : elements } return data | Convert Document to python dictionary . |
239,272 | def parse ( self , xmp ) : tree = etree . fromstring ( xmp ) rdf_tree = tree . find ( RDF_NS + 'RDF' ) meta = defaultdict ( dict ) for desc in rdf_tree . findall ( RDF_NS + 'Description' ) : for el in desc . getchildren ( ) : ns , tag = self . _parse_tag ( el ) value = self . _parse_value ( el ) meta [ ns ] [ tag ] = v... | Run parser and return a dictionary of all the parsed metadata . |
239,273 | def _parse_tag ( self , el ) : ns = None tag = el . tag if tag [ 0 ] == '{' : ns , tag = tag [ 1 : ] . split ( '}' , 1 ) if self . ns_map and ns in self . ns_map : ns = self . ns_map [ ns ] return ns , tag | Extract the namespace and tag from an element . |
239,274 | def _parse_value ( self , el ) : if el . find ( RDF_NS + 'Bag' ) is not None : value = [ ] for li in el . findall ( RDF_NS + 'Bag/' + RDF_NS + 'li' ) : value . append ( li . text ) elif el . find ( RDF_NS + 'Seq' ) is not None : value = [ ] for li in el . findall ( RDF_NS + 'Seq/' + RDF_NS + 'li' ) : value . append ( l... | Extract the metadata value from an element . |
239,275 | def parse_rsc_html ( htmlstring ) : converted = UnicodeDammit ( htmlstring ) if not converted . unicode_markup : raise UnicodeDecodeError ( 'Failed to detect encoding, tried [%s]' ) root = fromstring ( htmlstring , parser = HTMLParser ( recover = True , encoding = converted . original_encoding ) ) newp = None for child... | Messy RSC HTML needs this special parser to fix problems before creating selector . |
239,276 | def replace_rsc_img_chars ( document ) : image_re = re . compile ( 'http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\.gif' ) for img in document . xpath ( './/img[starts-with(@src, "http://www.rsc.org/images/entities/")]' ) : m = image_re . match ( img . get ( 'src' ) ) if... | Replace image characters with unicode equivalents . |
239,277 | def space_references ( document ) : for ref in document . xpath ( './/a/sup/span[@class="sup_ref"]' ) : a = ref . getparent ( ) . getparent ( ) if a is not None : atail = a . tail or '' if not atail . startswith ( ')' ) and not atail . startswith ( ',' ) and not atail . startswith ( ' ' ) : a . tail = ' ' + atail retur... | Ensure a space around reference links so there s a gap when they are removed . |
239,278 | def load ( ctx , input , output ) : log . debug ( 'chemdataextractor.cluster.load' ) import pickle click . echo ( 'Reading %s' % input . name ) clusters = { } for line in input . readlines ( ) : cluster , word , freq = line . split ( ) clusters [ word ] = cluster pickle . dump ( clusters , output , protocol = pickle . ... | Read clusters from file and save to model file . |
239,279 | def space_labels ( document ) : for label in document . xpath ( './/bold' ) : if not label . text or not re . match ( '^\(L?\d\d?[a-z]?\):?$' , label . text , re . I ) : continue parent = label . getparent ( ) previous = label . getprevious ( ) if previous is None : text = parent . text or '' if not text . endswith ( '... | Ensure space around bold compound labels . |
239,280 | def tidy_nlm_references ( document ) : def strip_preceding ( text ) : stext = text . rstrip ( ) if stext . endswith ( '[' ) or stext . endswith ( '(' ) : return stext [ : - 1 ] return text def strip_between ( text ) : stext = text . strip ( ) if stext in { ',' , '-' , '\u2013' , '\u2212' } : return '' return text def s... | Remove punctuation around references like brackets commas hyphens . |
239,281 | def regex_span_tokenize ( s , regex ) : left = 0 for m in re . finditer ( regex , s , re . U ) : right , next = m . span ( ) if right != 0 : yield left , right left = next yield left , len ( s ) | Return spans that identify tokens in s split using regex . |
239,282 | def tokenize ( self , s ) : return [ s [ start : end ] for start , end in self . span_tokenize ( s ) ] | Return a list of token strings from the given sentence . |
239,283 | def span_tokenize ( self , s ) : if self . _tokenizer is None : self . _tokenizer = load_model ( self . model ) return self . _tokenizer . span_tokenize ( s ) | Return a list of integer offsets that identify sentences in the given text . |
239,284 | def _split_span ( self , span , index , length = 0 ) : offset = span [ 1 ] + index if index < 0 else span [ 0 ] + index return [ ( span [ 0 ] , offset ) , ( offset , offset + length ) , ( offset + length , span [ 1 ] ) ] | Split a span into two or three separate spans at certain indices . |
239,285 | def _closing_bracket_index ( self , text , bpair = ( '(' , ')' ) ) : level = 1 for i , char in enumerate ( text [ 1 : ] ) : if char == bpair [ 0 ] : level += 1 elif char == bpair [ 1 ] : level -= 1 if level == 0 : return i + 1 | Return the index of the closing bracket that matches the opening bracket at the start of the text . |
239,286 | def _opening_bracket_index ( self , text , bpair = ( '(' , ')' ) ) : level = 1 for i , char in enumerate ( reversed ( text [ : - 1 ] ) ) : if char == bpair [ 1 ] : level += 1 elif char == bpair [ 0 ] : level -= 1 if level == 0 : return len ( text ) - i - 2 | Return the index of the opening bracket that matches the closing bracket at the end of the text . |
239,287 | def _is_saccharide_arrow ( self , before , after ) : if ( before and after and before [ - 1 ] . isdigit ( ) and after [ 0 ] . isdigit ( ) and before . rstrip ( '0123456789' ) . endswith ( '(' ) and after . lstrip ( '0123456789' ) . startswith ( ')-' ) ) : return True else : return False | Return True if the arrow is in a chemical name . |
239,288 | def get_names ( cs ) : records = [ ] for c in cs : records . extend ( c . get ( 'names' , [ ] ) ) return records | Return list of every name . |
239,289 | def get_labels ( cs ) : records = [ ] for c in cs : records . extend ( c . get ( 'labels' , [ ] ) ) return records | Return list of every label . |
239,290 | def get_ids ( cs ) : records = [ ] for c in cs : records . append ( { k : c [ k ] for k in c if k in { 'names' , 'labels' } } ) return records | Return chemical identifier records . |
239,291 | def memoized_property ( fget ) : attr_name = '_{}' . format ( fget . __name__ ) @ functools . wraps ( fget ) def fget_memoized ( self ) : if not hasattr ( self , attr_name ) : setattr ( self , attr_name , fget ( self ) ) return getattr ( self , attr_name ) return property ( fget_memoized ) | Decorator to create memoized properties . |
239,292 | def memoize ( obj ) : cache = obj . cache = { } @ functools . wraps ( obj ) def memoizer ( * args , ** kwargs ) : if args not in cache : cache [ args ] = obj ( * args , ** kwargs ) return cache [ args ] return memoizer | Decorator to create memoized functions methods or classes . |
239,293 | def evaluate ( self , gold ) : tagged_sents = self . tag_sents ( [ w for ( w , t ) in sent ] for sent in gold ) gold_tokens = sum ( gold , [ ] ) test_tokens = sum ( tagged_sents , [ ] ) accuracy = float ( sum ( x == y for x , y in six . moves . zip ( gold_tokens , test_tokens ) ) ) / len ( test_tokens ) return accuracy | Evaluate the accuracy of this tagger using a gold standard corpus . |
239,294 | def predict ( self , features ) : scores = defaultdict ( float ) for feat in features : if feat not in self . weights : continue weights = self . weights [ feat ] for label , weight in weights . items ( ) : scores [ label ] += weight return max ( self . classes , key = lambda label : ( scores [ label ] , label ) ) | Dot - product the features and current weights and return the best label . |
239,295 | def update ( self , truth , guess , features ) : def upd_feat ( c , f , w , v ) : param = ( f , c ) self . _totals [ param ] += ( self . i - self . _tstamps [ param ] ) * w self . _tstamps [ param ] = self . i self . weights [ f ] [ c ] = w + v self . i += 1 if truth == guess : return None for f in features : weights =... | Update the feature weights . |
239,296 | def average_weights ( self ) : for feat , weights in self . weights . items ( ) : new_feat_weights = { } for clas , weight in weights . items ( ) : param = ( feat , clas ) total = self . _totals [ param ] total += ( self . i - self . _tstamps [ param ] ) * weight averaged = round ( total / float ( self . i ) , 3 ) if a... | Average weights from all iterations . |
239,297 | def save ( self , path ) : with io . open ( path , 'wb' ) as fout : return pickle . dump ( dict ( self . weights ) , fout ) | Save the pickled model weights . |
239,298 | def load ( self , path ) : with io . open ( path , 'rb' ) as fin : self . weights = pickle . load ( fin ) | Load the pickled model weights . |
239,299 | def train ( self , sentences , nr_iter = 5 ) : self . _make_tagdict ( sentences ) self . perceptron . classes = self . classes for iter_ in range ( nr_iter ) : c = 0 n = 0 for sentence in sentences : prev , prev2 = self . START context = [ t [ 0 ] for t in sentence ] for i , ( token , tag ) in enumerate ( sentence ) : ... | Train a model from sentences . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.