idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
15,300
def cmd ( send , msg , args ) : key = args [ 'config' ] [ 'api' ] [ 'bitlykey' ] parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--blacklist' ) parser . add_argument ( '--unblacklist' ) try : cmdargs , msg = parser . parse_known_args ( msg ) msg = ' ' . join ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if cmdargs . blacklist : if args [ 'is_admin' ] ( args [ 'nick' ] ) : send ( blacklist_word ( args [ 'db' ] , cmdargs . blacklist ) ) else : send ( "Blacklisting is admin-only" ) elif cmdargs . unblacklist : if args [ 'is_admin' ] ( args [ 'nick' ] ) : send ( unblacklist_word ( args [ 'db' ] , cmdargs . unblacklist ) ) else : send ( "Unblacklisting is admin-only" ) else : defn , url = get_urban ( msg , args [ 'db' ] , key ) send ( defn ) if url : send ( "See full definition at %s" % url )
Gets a definition from urban dictionary .
276
8
15,301
def people ( self ) : people_response = self . get_request ( 'people/' ) return [ Person ( self , pjson [ 'user' ] ) for pjson in people_response ]
Generates a list of all People .
43
8
15,302
def tasks ( self ) : tasks_response = self . get_request ( 'tasks/' ) return [ Task ( self , tjson [ 'task' ] ) for tjson in tasks_response ]
Generates a list of all Tasks .
44
9
15,303
def clients ( self ) : clients_response = self . get_request ( 'clients/' ) return [ Client ( self , cjson [ 'client' ] ) for cjson in clients_response ]
Generates a list of all Clients .
44
9
15,304
def get_client ( self , client_id ) : client_response = self . get_request ( 'clients/%s' % client_id ) return Client ( self , client_response [ 'client' ] )
Gets a single client by id .
48
8
15,305
def get_project ( self , project_id ) : project_response = self . get_request ( 'projects/%s' % project_id ) return Project ( self , project_response [ 'project' ] )
Gets a single project by id .
47
8
15,306
def create_person ( self , first_name , last_name , email , department = None , default_rate = None , admin = False , contractor = False ) : person = { 'user' : { 'first_name' : first_name , 'last_name' : last_name , 'email' : email , 'department' : department , 'default_hourly_rate' : default_rate , 'is_admin' : admin , 'is_contractor' : contractor , } } response = self . post_request ( 'people/' , person , follow = True ) if response : return Person ( self , response [ 'user' ] )
Creates a Person with the given information .
143
9
15,307
def create_project ( self , name , client_id , budget = None , budget_by = 'none' , notes = None , billable = True ) : project = { 'project' : { 'name' : name , 'client_id' : client_id , 'budget_by' : budget_by , 'budget' : budget , 'notes' : notes , 'billable' : billable , } } response = self . post_request ( 'projects/' , project , follow = True ) if response : return Project ( self , response [ 'project' ] )
Creates a Project with the given information .
125
9
15,308
def create_client ( self , name ) : client = { 'client' : { 'name' : name , } } response = self . post_request ( 'clients/' , client , follow = True ) if response : return Client ( self , response [ 'client' ] )
Creates a Client with the given information .
61
9
15,309
def delete ( self ) : response = self . hv . delete_request ( 'people/' + str ( self . id ) ) return response
Deletes the person immediately .
31
6
15,310
def task_assignments ( self ) : url = str . format ( 'projects/{}/task_assignments' , self . id ) response = self . hv . get_request ( url ) return [ TaskAssignment ( self . hv , tj [ 'task_assignment' ] ) for tj in response ]
Retrieves all tasks currently assigned to this project .
74
11
15,311
def partial ( cls , prefix , source ) : match = prefix + "." matches = cls ( [ ( key [ len ( match ) : ] , source [ key ] ) for key in source if key . startswith ( match ) ] ) if not matches : raise ValueError ( ) return matches
Strip a prefix from the keys of another dictionary returning a Bunch containing only valid key value pairs .
64
21
15,312
def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--nick' , action = arguments . NickParser ) parser . add_argument ( '--ignore-case' , '-i' , action = 'store_true' ) parser . add_argument ( 'string' , nargs = '*' ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if not cmdargs . string : send ( 'Please specify a search term.' ) return cmdchar = args [ 'config' ] [ 'core' ] [ 'cmdchar' ] term = ' ' . join ( cmdargs . string ) if cmdargs . nick : query = args [ 'db' ] . query ( Log ) . filter ( Log . type == 'pubmsg' , Log . source == cmdargs . nick , ~ Log . msg . startswith ( cmdchar ) ) else : query = args [ 'db' ] . query ( Log ) . filter ( Log . type == 'pubmsg' , ~ Log . msg . startswith ( cmdchar ) ) if cmdargs . ignore_case : query = query . filter ( Log . msg . ilike ( '%%%s%%' % escape ( term ) ) ) else : query = query . filter ( Log . msg . like ( '%%%s%%' % escape ( term ) ) ) query = query . order_by ( Log . time . desc ( ) ) result = query . limit ( 1 ) . first ( ) count = query . count ( ) if result is not None : logtime = result . time . strftime ( '%Y-%m-%d %H:%M:%S' ) send ( "%s was last said by %s at %s (%d occurrences)" % ( result . msg , result . source , logtime , count ) ) elif cmdargs . nick : send ( '%s has never said %s.' % ( cmdargs . nick , term ) ) else : send ( '%s has never been said.' % term )
Greps the log for a string .
464
8
15,313
def pick_action_todo ( ) : for ndx , todo in enumerate ( things_to_do ) : #print('todo = ', todo) if roll_dice ( todo [ "chance" ] ) : cur_act = actions [ get_action_by_name ( todo [ "name" ] ) ] if todo [ "WHERE_COL" ] == "energy" and my_char [ "energy" ] > todo [ "WHERE_VAL" ] : return cur_act if todo [ "WHERE_COL" ] == "gold" and my_char [ "gold" ] > todo [ "WHERE_VAL" ] : return cur_act return actions [ 3 ]
only for testing and AI - user will usually choose an action Sort of works
156
15
15,314
def do_action ( character , action ) : stats = "Energy=" + str ( round ( character [ "energy" ] , 0 ) ) + ", " stats += "Gold=" + str ( round ( character [ "gold" ] , 0 ) ) + ", " ndx_action_skill = get_skill_by_name ( action [ "name" ] , character ) stats += "Skill=" + str ( round ( character [ "skills" ] [ ndx_action_skill ] [ "level" ] , 1 ) ) my_char [ "energy" ] -= action [ "cost_energy" ] my_char [ "skills" ] [ ndx_action_skill ] [ "level" ] += action [ "exp_gain" ] # NOT NEEDED act = get_action_by_name(character["skills"][ndx_action_skill]["name"]) reward_item = action [ "reward_item" ] #print('reward_item = ', reward_item) #print('action = ', action) inv = get_inventory_by_name ( reward_item , my_char ) #print('inv=', inv) if roll_dice ( action [ "reward_chance" ] ) : my_char [ "inventory" ] [ inv ] [ "val" ] += 1 #my_char["inventory"][inv] += 1 #my_char["inventory"][inv][reward_item] += 1 print ( character [ "name" ] + " is " + action [ "name" ] + ". " + stats + ' FOUND ' + reward_item ) else : print ( character [ "name" ] + " is " + action [ "name" ] + ". " + stats )
called by main game loop to run an action
378
9
15,315
def get_inventory_by_name ( nme , character ) : for ndx , sk in enumerate ( character [ "inventory" ] ) : #print("sk = ", sk, " , nme = ", nme) if sk [ "name" ] == nme : return ndx return 0
returns the inventory index by name
65
7
15,316
def get_skill_by_name ( nme , character ) : for ndx , sk in enumerate ( character [ "skills" ] ) : if sk [ "name" ] == nme : return ndx return 0
returns the skill by name in a character
49
9
15,317
def attribute_checker ( operator , attribute , value = '' ) : return { '=' : lambda el : el . get ( attribute ) == value , # attribute includes value as one of a set of space separated tokens '~' : lambda el : value in el . get ( attribute , '' ) . split ( ) , # attribute starts with value '^' : lambda el : el . get ( attribute , '' ) . startswith ( value ) , # attribute ends with value '$' : lambda el : el . get ( attribute , '' ) . endswith ( value ) , # attribute contains value '*' : lambda el : value in el . get ( attribute , '' ) , # attribute is either exactly value or starts with value- '|' : lambda el : el . get ( attribute , '' ) == value or el . get ( attribute , '' ) . startswith ( '%s-' % value ) , } . get ( operator , lambda el : el . has_key ( attribute ) )
Takes an operator attribute and optional value ; returns a function that will return True for elements that match that combination .
213
23
15,318
def select ( soup , selector ) : tokens = selector . split ( ) current_context = [ soup ] for token in tokens : m = attribselect_re . match ( token ) if m : # Attribute selector tag , attribute , operator , value = m . groups ( ) if not tag : tag = True checker = attribute_checker ( operator , attribute , value ) found = [ ] for context in current_context : found . extend ( [ el for el in context . findAll ( tag ) if checker ( el ) ] ) current_context = found continue if '#' in token : # ID selector tag , id = token . split ( '#' , 1 ) if not tag : tag = True el = current_context [ 0 ] . find ( tag , { 'id' : id } ) if not el : return [ ] # No match current_context = [ el ] continue if '.' in token : # Class selector tag , klass = token . split ( '.' , 1 ) if not tag : tag = True found = [ ] for context in current_context : found . extend ( context . findAll ( tag , { 'class' : lambda attr : attr and klass in attr . split ( ) } ) ) current_context = found continue if token == '*' : # Star selector found = [ ] for context in current_context : found . extend ( context . findAll ( True ) ) current_context = found continue # Here we should just have a regular tag if not tag_re . match ( token ) : return [ ] found = [ ] for context in current_context : found . extend ( context . findAll ( token ) ) current_context = found return current_context
soup should be a BeautifulSoup instance ; selector is a CSS selector specifying the elements you want to retrieve .
367
23
15,319
def gradient ( self , P , Q , Y , i ) : return 4 * sum ( [ ( P [ i , j ] - Q [ i , j ] ) * ( Y [ i ] - Y [ j ] ) * ( 1 + np . linalg . norm ( Y [ i ] - Y [ j ] ) ** 2 ) ** - 1 for j in range ( Y . shape [ 0 ] ) ] )
Computes the gradient of KL divergence with respect to the i th example of Y
89
16
15,320
def try_ ( block , except_ = None , else_ = None , finally_ = None ) : ensure_callable ( block ) if not ( except_ or else_ or finally_ ) : raise TypeError ( "at least one of `except_`, `else_` or `finally_` " "functions must be provided" ) if else_ and not except_ : raise TypeError ( "`else_` can only be provided along with `except_`" ) if except_ : if callable ( except_ ) : except_ = [ ( Exception , except_ ) ] else : ensure_iterable ( except_ ) if is_mapping ( except_ ) : ensure_ordered_mapping ( except_ ) except_ = except_ . items ( ) def handle_exception ( ) : """Dispatch current exception to proper handler in ``except_``.""" exc_type , exc_object = sys . exc_info ( ) [ : 2 ] for t , handler in except_ : if issubclass ( exc_type , t ) : return handler ( exc_object ) raise if else_ : ensure_callable ( else_ ) if finally_ : ensure_callable ( finally_ ) try : block ( ) except : return handle_exception ( ) else : return else_ ( ) finally : finally_ ( ) else : try : block ( ) except : return handle_exception ( ) else : return else_ ( ) else : if finally_ : ensure_callable ( finally_ ) try : return block ( ) except : return handle_exception ( ) finally : finally_ ( ) else : try : return block ( ) except : return handle_exception ( ) elif finally_ : ensure_callable ( finally_ ) try : return block ( ) finally : finally_ ( )
Emulate a try block .
385
6
15,321
def with_ ( contextmanager , do ) : ensure_contextmanager ( contextmanager ) ensure_callable ( do ) with contextmanager as value : return do ( value )
Emulate a with statement performing an operation within context .
36
11
15,322
def _cast_repr ( self , caster , * args , * * kwargs ) : if self . __repr_content is None : self . __repr_content = hash_and_truncate ( self ) assert self . __uses_default_repr # Sanity check: we are indeed using the default repr here. If this has ever changed, something went wrong. return caster ( self . __repr_content , * args , * * kwargs )
Will cast this constant with the provided caster passing args and kwargs .
104
15
15,323
def cmd ( send , * _ ) : thread_names = [ ] for x in sorted ( threading . enumerate ( ) , key = lambda k : k . name ) : res = re . match ( r'Thread-(\d+$)' , x . name ) if res : tid = int ( res . group ( 1 ) ) # Handle the main server thread (permanently listed as _worker) if x . _target . __name__ == '_worker' : thread_names . append ( ( tid , "%s running server thread" % x . name ) ) # Handle the multiprocessing pool worker threads (they don't have names beyond Thread-x) elif x . _target . __module__ == 'multiprocessing.pool' : thread_names . append ( ( tid , "%s running multiprocessing pool worker thread" % x . name ) ) # Handle everything else including MainThread and deferred threads else : res = re . match ( r'Thread-(\d+)' , x . name ) tid = 0 if res : tid = int ( res . group ( 1 ) ) thread_names . append ( ( tid , x . name ) ) for x in sorted ( thread_names , key = lambda k : k [ 0 ] ) : send ( x [ 1 ] )
Enumerate threads .
280
5
15,324
def pipe ( ) : try : from os import pipe return pipe ( ) except : pipe = Pipe ( ) return pipe . reader_fd , pipe . writer_fd
Return the optimum pipe implementation for the capabilities of the active system .
34
13
15,325
def read ( self ) : try : return self . reader . recv ( 1 ) except socket . error : ex = exception ( ) . exception if ex . args [ 0 ] == errno . EWOULDBLOCK : raise IOError raise
Emulate a file descriptors read method
50
8
15,326
def replace_all ( text , dic ) : for i , j in dic . iteritems ( ) : text = text . replace ( i , j ) return text
Takes a string and dictionary . replaces all occurrences of i with j
36
14
15,327
def replace_u_start_month ( month ) : month = month . lstrip ( '-' ) if month == 'uu' or month == '0u' : return '01' if month == 'u0' : return '10' return month . replace ( 'u' , '0' )
Find the earliest legitimate month .
65
6
15,328
def replace_u_end_month ( month ) : month = month . lstrip ( '-' ) if month == 'uu' or month == '1u' : return '12' if month == 'u0' : return '10' if month == '0u' : return '09' if month [ 1 ] in [ '1' , '2' ] : # 'u1' or 'u2' return month . replace ( 'u' , '1' ) # Otherwise it should match r'u[3-9]'. return month . replace ( 'u' , '0' )
Find the latest legitimate month .
130
6
15,329
def replace_u_start_day ( day ) : day = day . lstrip ( '-' ) if day == 'uu' or day == '0u' : return '01' if day == 'u0' : return '10' return day . replace ( 'u' , '0' )
Find the earliest legitimate day .
65
6
15,330
def replace_u_end_day ( day , year , month ) : day = day . lstrip ( '-' ) year = int ( year ) month = int ( month . lstrip ( '-' ) ) if day == 'uu' or day == '3u' : # Use the last day of the month for a given year/month. return str ( calendar . monthrange ( year , month ) [ 1 ] ) if day == '0u' or day == '1u' : return day . replace ( 'u' , '9' ) if day == '2u' or day == 'u9' : if month != '02' or calendar . isleap ( year ) : return '29' elif day == '2u' : # It is Feburary and not a leap year. return '28' else : # It is February, not a leap year, day ends in 9. return '19' # 'u2' 'u3' 'u4' 'u5' 'u6' 'u7' 'u8' if 1 < int ( day [ 1 ] ) < 9 : return day . replace ( 'u' , '2' ) # 'u0' 'u1' if day == 'u1' : if calendar . monthrange ( year , month ) [ 1 ] == 31 : # See if the month has a 31st. return '31' else : return '21' if day == 'u0' : if calendar . monthrange ( year , month ) [ 1 ] >= 30 : return '30' else : return '20'
Find the latest legitimate day .
341
6
15,331
def replace_u ( matchobj ) : pieces = list ( matchobj . groups ( '' ) ) # Replace "u"s in start and end years. if 'u' in pieces [ 1 ] : pieces [ 1 ] = pieces [ 1 ] . replace ( 'u' , '0' ) if 'u' in pieces [ 5 ] : pieces [ 5 ] = pieces [ 5 ] . replace ( 'u' , '9' ) # Replace "u"s in start month. if 'u' in pieces [ 2 ] : pieces [ 2 ] = '-' + replace_u_start_month ( pieces [ 2 ] ) # Replace "u"s in end month. if 'u' in pieces [ 6 ] : pieces [ 6 ] = '-' + replace_u_end_month ( pieces [ 6 ] ) # Replace "u"s in start day. if 'u' in pieces [ 3 ] : pieces [ 3 ] = '-' + replace_u_start_day ( pieces [ 3 ] ) # Replace "u"s in end day. if 'u' in pieces [ 7 ] : pieces [ 7 ] = '-' + replace_u_end_day ( pieces [ 7 ] , year = pieces [ 5 ] , month = pieces [ 6 ] ) return '' . join ( ( '' . join ( pieces [ : 4 ] ) , '/' , '' . join ( pieces [ 4 : ] ) ) )
Break the interval into parts and replace u s .
303
10
15,332
def zero_year_special_case ( from_date , to_date , start , end ) : if start == 'pos' and end == 'pos' : # always interval from earlier to later if from_date . startswith ( '0000' ) and not to_date . startswith ( '0000' ) : return True # always interval from later to earlier if not from_date . startswith ( '0000' ) and to_date . startswith ( '0000' ) : return False # an interval from 0000-MM-DD/0000-MM-DD ??? PARSE !!! if from_date . startswith ( '0000' ) and to_date . startswith ( '0000' ) : # fill from date assuming first subsequent date object if missing # missing m+d, assume jan 1 if len ( from_date ) == 4 : fm , fd = 1 , 1 # missing d, assume the 1st elif len ( from_date ) == 7 : fm , fd = int ( from_date [ 5 : 7 ] ) , 1 # not missing any date objects elif len ( from_date ) == 10 : fm , fd = int ( from_date [ 5 : 7 ] ) , int ( from_date [ 8 : 10 ] ) # fill to date assuming first subsequent date object if missing # missing m+d, assume jan 1 if len ( to_date ) == 4 : tm , td = 1 , 1 # missing d, assume the 1st elif len ( to_date ) == 7 : tm , td = int ( to_date [ 5 : 7 ] ) , 1 # not missing any date objects elif len ( to_date ) == 10 : tm , td = int ( to_date [ 5 : 7 ] ) , int ( to_date [ 8 : 10 ] ) # equality check if from_date == to_date : return True # compare the dates if fm <= tm : if fd <= td : return True else : return False else : return False # these cases are always one way or the other # "-0000" is an invalid edtf elif start == 'neg' and end == 'neg' : return False # False unless start is not "0000" elif start == 'neg' and end == 'pos' : if from_date . startswith ( "0000" ) : return False else : return True
strptime does not resolve a 0000 year we must handle this .
518
14
15,333
def is_valid_interval ( edtf_candidate ) : # resolve interval into from / to datetime objects from_date = None to_date = None # initialize interval flags for special cases, assume positive end , start = 'pos' , 'pos' if edtf_candidate . count ( '/' ) == 1 : # replace all 'problem' cases (unspecified, 0000 date, ?~, -, y) # break the interval into two date strings edtf_candidate = replace_all ( edtf_candidate , interval_replacements ) edtf_candidate = re . sub ( U_PATTERN , replace_u , edtf_candidate ) parts = edtf_candidate . split ( '/' ) # set flag for negative start date if parts [ 0 ] . startswith ( "-" ) : start = 'neg' parts [ 0 ] = parts [ 0 ] [ 1 : ] # set flag for negative end date if parts [ 1 ] . startswith ( "-" ) : end = 'neg' parts [ 1 ] = parts [ 1 ] [ 1 : ] # if starts positive and ends negative, that's always False if start == 'pos' and end == 'neg' : return False # handle special case of 0000 year if parts [ 0 ] . startswith ( "0000" ) or parts [ 1 ] . startswith ( "0000" ) : return zero_year_special_case ( parts [ 0 ] , parts [ 1 ] , start , end ) # 2 '-' characters means we are matching year-month-day if parts [ 0 ] . count ( "-" ) == 2 : from_date = datetime . datetime . strptime ( parts [ 0 ] , "%Y-%m-%d" ) if parts [ 1 ] . count ( "-" ) == 2 : to_date = datetime . datetime . strptime ( parts [ 1 ] , "%Y-%m-%d" ) # 1 '-' character means we are match year-month if parts [ 0 ] . count ( "-" ) == 1 : from_date = datetime . datetime . strptime ( parts [ 0 ] , "%Y-%m" ) if parts [ 1 ] . count ( "-" ) == 1 : to_date = datetime . datetime . strptime ( parts [ 1 ] , "%Y-%m" ) # zero '-' characters means we are matching a year if parts [ 0 ] . count ( "-" ) == 0 : # if from_date is unknown, we can assume the lowest possible date if parts [ 0 ] == 'unknown' : from_date = datetime . datetime . strptime ( "0001" , "%Y" ) else : from_date = datetime . datetime . strptime ( parts [ 0 ] , "%Y" ) if parts [ 1 ] . count ( "-" ) == 0 : # when the to_date is open and the from_date is valid, it's valid if parts [ 1 ] == 'open' or parts [ 1 ] == 'unknown' : to_date = 'open' else : to_date = datetime . datetime . strptime ( parts [ 1 ] , "%Y" ) # if it starts negative and ends positive, that's always True if start == 'neg' and end == 'pos' : return True # if start and end are negative, the from_date must be >= to_date elif start == 'neg' and end == 'neg' : if from_date >= to_date and from_date and to_date : return True # if the to_date is unknown or open, it could be any date, therefore elif ( parts [ 1 ] == 'unknown' or parts [ 1 ] == 'open' or parts [ 0 ] == 'unknown' ) : return True # if start and end are positive, the from_date must be <= to_date elif start == 'pos' and end == 'pos' : if from_date <= to_date and from_date and to_date : return True else : return False else : return False
Test to see if the edtf candidate is a valid interval
886
12
15,334
def isLevel2 ( edtf_candidate ) : if "[" in edtf_candidate or "{" in edtf_candidate : result = edtf_candidate == level2Expression elif " " in edtf_candidate : result = False else : result = edtf_candidate == level2Expression return result
Checks to see if the date is level 2 valid
73
11
15,335
def is_valid ( edtf_candidate ) : if ( isLevel0 ( edtf_candidate ) or isLevel1 ( edtf_candidate ) or isLevel2 ( edtf_candidate ) ) : if '/' in edtf_candidate : return is_valid_interval ( edtf_candidate ) else : return True else : return False
isValid takes a candidate date and returns if it is valid or not
80
14
15,336
def is_direct_subclass ( class_ , of ) : ensure_class ( class_ ) ensure_class ( of ) # TODO(xion): support predicates in addition to classes return of in class_ . __bases__
Check whether given class is a direct subclass of the other .
51
12
15,337
def ensure_direct_subclass ( class_ , of ) : if not is_direct_subclass ( class_ , of ) : raise TypeError ( "expected a direct subclass of %r, got %s instead" % ( of , class_ . __name__ ) ) return class_
Check whether given class is a direct subclass of another .
62
11
15,338
def main ( ) : print ( "|---------------------------------------------------" ) print ( "| Virtual AI Simulator" ) print ( "|---------------------------------------------------" ) print ( "| " ) print ( "| r = rebuild planets c = create character" ) print ( "| s = simulation o = create opponent" ) print ( "| q = quit b = battle characters" ) print ( "| " ) planets = load_planet_list ( ) show_planet_shortlist ( planets ) print ( "|---------------------------------------------------" ) cmd = input ( '| Enter choice ?' ) if cmd == 'r' : rebuild_planet_samples ( ) elif cmd == 'q' : exit ( 0 ) elif cmd < str ( len ( planets ) + 1 ) and cmd > '0' : fname = planets [ int ( cmd ) - 1 ] [ 'name' ] + '.txt' print ( 'viewing planet ' + fname ) view_world . display_map ( fldr + os . sep + fname ) elif cmd == 'c' : c1 = create_character ( ) elif cmd == 'o' : c2 = create_character ( ) elif cmd == 'b' : run_simulation ( c1 , c2 ) elif cmd == 's' : print ( 'not implemented' ) else : print ( 'invalid command ' + cmd ) main ( )
test program for VAIS . Generates several planets and populates with animals and plants . Then places objects and tests the sequences .
298
26
15,339
def load_planet_list ( ) : planet_list = [ ] with open ( fldr + os . sep + 'planet_samples.csv' ) as f : hdr = f . readline ( ) for line in f : #print("Building ", line) name , num_seeds , width , height , wind , rain , sun , lava = parse_planet_row ( line ) planet_list . append ( { 'name' : name , 'num_seeds' : num_seeds , 'width' : width , 'height' : height , 'wind' : wind , 'rain' : rain , 'sun' : sun , 'lava' : lava } ) return planet_list
load the list of prebuilt planets
153
7
15,340
def create_character ( ) : traits = character . CharacterCollection ( character . fldr ) c = traits . generate_random_character ( ) print ( c ) return c
create a random character
37
4
15,341
def run_simulation ( c1 , c2 ) : print ( 'running simulation...' ) traits = character . CharacterCollection ( character . fldr ) c1 = traits . generate_random_character ( ) c2 = traits . generate_random_character ( ) print ( c1 ) print ( c2 ) rules = battle . BattleRules ( battle . rules_file ) b = battle . Battle ( c1 , c2 , traits , rules , print_console = 'Yes' ) print ( b . status )
using character and planet run the simulation
111
7
15,342
def name_replace ( self , to_replace , replacement ) : self . name = self . name . replace ( to_replace , replacement )
Replaces part of tag name with new value
30
9
15,343
def cmd ( send , msg , args ) : if not msg : send ( "Seen who?" ) return cmdchar , ctrlchan = args [ 'config' ] [ 'core' ] [ 'cmdchar' ] , args [ 'config' ] [ 'core' ] [ 'ctrlchan' ] last = get_last ( args [ 'db' ] , cmdchar , ctrlchan , msg ) if last is None : send ( "%s has never shown their face." % msg ) return delta = datetime . now ( ) - last . time # We only need second-level precision. delta -= delta % timedelta ( seconds = 1 ) output = "%s was last seen %s ago " % ( msg , delta ) if last . type == 'pubmsg' or last . type == 'privmsg' : output += 'saying "%s"' % last . msg elif last . type == 'action' : output += 'doing "%s"' % last . msg elif last . type == 'part' : output += 'leaving and saying "%s"' % last . msg elif last . type == 'nick' : output += 'nicking to %s' % last . msg elif last . type == 'quit' : output += 'quiting and saying "%s"' % last . msg elif last . type == 'kick' : output += 'kicking %s for "%s"' % last . msg . split ( ',' ) elif last . type == 'topic' : output += 'changing topic to %s' % last . msg elif last . type in [ 'pubnotice' , 'privnotice' ] : output += 'sending notice %s' % last . msg elif last . type == 'mode' : output += 'setting mode %s' % last . msg else : raise Exception ( "Invalid type." ) send ( output )
When a nick was last seen .
399
7
15,344
def cmd ( send , msg , args ) : if not msg : msg = gen_word ( ) morse = gen_morse ( msg ) if len ( morse ) > 100 : send ( "Your morse is too long. Have you considered Western Union?" ) else : send ( morse )
Converts text to morse code .
64
8
15,345
def ellipsis ( text , length , symbol = "..." ) : if len ( text ) > length : pos = text . rfind ( " " , 0 , length ) if pos < 0 : return text [ : length ] . rstrip ( "." ) + symbol else : return text [ : pos ] . rstrip ( "." ) + symbol else : return text
Present a block of text of given length . If the length of available text exceeds the requested length truncate and intelligently append an ellipsis .
78
30
15,346
def cmd ( send , msg , args ) : result = args [ 'db' ] . query ( Urls ) . order_by ( func . random ( ) ) . first ( ) send ( "%s" % result . url )
Reposts a url .
49
6
15,347
def get_elections ( self , obj ) : election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] ) elections = Election . objects . filter ( race__office = obj , election_day = election_day ) return ElectionSerializer ( elections , many = True ) . data
All elections on an election day .
70
7
15,348
def get_content ( self , obj ) : election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] ) return PageContent . objects . office_content ( election_day , obj )
All content for office s page on an election day .
50
11
15,349
def cmd ( send , msg , args ) : try : args [ 'handler' ] . workers . cancel ( int ( msg ) ) except ValueError : send ( "Index must be a digit." ) return except KeyError : send ( "No such event." ) return send ( "Event canceled." )
Cancels a deferred action with the given id .
63
11
15,350
def cmd ( send , msg , _ ) : if not msg : msg = randrange ( 5000 ) elif not msg . isdigit ( ) : send ( "Invalid Number." ) return send ( gen_roman ( int ( msg ) ) )
Convert a number to the roman numeral equivalent .
51
12
15,351
def cmd ( send , msg , args ) : if not msg : send ( "kill who?" ) return if msg . lower ( ) == args [ 'botnick' ] . lower ( ) : send ( '%s is not feeling suicidal right now.' % msg ) else : send ( 'Die, %s!' % msg )
Kills somebody .
69
4
15,352
def cmd ( send , msg , args ) : cmdchar = args [ 'config' ] [ 'core' ] [ 'cmdchar' ] if msg : if msg . startswith ( cmdchar ) : msg = msg [ len ( cmdchar ) : ] if len ( msg . split ( ) ) > 1 : send ( "One argument only" ) elif not command_registry . is_registered ( msg ) : send ( "Not a module." ) else : doc = command_registry . get_command ( msg ) . get_doc ( ) if doc is None : send ( "No documentation found." ) else : for line in doc . splitlines ( ) : send ( line . format ( command = cmdchar + msg ) , target = args [ 'nick' ] ) else : modules = sorted ( command_registry . get_enabled_commands ( ) ) cmdlist = ( ' %s' % cmdchar ) . join ( modules ) send ( 'Commands: %s%s' % ( cmdchar , cmdlist ) , target = args [ 'nick' ] , ignore_length = True ) send ( '%shelp <command> for more info on a command.' % cmdchar , target = args [ 'nick' ] )
Gives help .
268
4
15,353
def plugin ( module , * args , * * kwargs ) : def wrap ( f ) : m = module ( f , * args , * * kwargs ) if inspect . isclass ( m ) : for k , v in m . __dict__ . items ( ) : if not k . startswith ( "__" ) : setattr ( f , k , v ) elif inspect . isfunction ( m ) : setattr ( f , kls . __name__ , m ) return f return wrap
Decorator to extend a package to a view . The module can be a class or function . It will copy all the methods to the class
110
29
15,354
def template ( page = None , layout = None , * * kwargs ) : pkey = "_template_extends__" def decorator ( f ) : if inspect . isclass ( f ) : layout_ = layout or page extends = kwargs . pop ( "extends" , None ) if extends and hasattr ( extends , pkey ) : items = getattr ( extends , pkey ) . items ( ) if "layout" in items : layout_ = items . pop ( "layout" ) for k , v in items : kwargs . setdefault ( k , v ) if not layout_ : layout_ = "layout.html" kwargs . setdefault ( "brand_name" , "" ) kwargs [ "layout" ] = layout_ setattr ( f , pkey , kwargs ) setattr ( f , "base_layout" , kwargs . get ( "layout" ) ) f . g ( TEMPLATE_CONTEXT = kwargs ) return f else : @ functools . wraps ( f ) def wrap ( * args2 , * * kwargs2 ) : response = f ( * args2 , * * kwargs2 ) if isinstance ( response , dict ) or response is None : response = response or { } if page : response . setdefault ( "template_" , page ) if layout : response . setdefault ( "layout_" , layout ) for k , v in kwargs . items ( ) : response . setdefault ( k , v ) return response return wrap return decorator
Decorator to change the view template and layout .
337
11
15,355
def merge ( s , t ) : for k , v in t . items ( ) : if isinstance ( v , dict ) : if k not in s : s [ k ] = v continue s [ k ] = merge ( s [ k ] , v ) continue s [ k ] = v return s
Merge dictionary t into s .
64
7
15,356
def load_object ( target , namespace = None ) : if namespace and ':' not in target : allowable = dict ( ( i . name , i ) for i in pkg_resources . iter_entry_points ( namespace ) ) if target not in allowable : raise ValueError ( 'Unknown plugin "' + target + '"; found: ' + ', ' . join ( allowable ) ) return allowable [ target ] . load ( ) parts , target = target . split ( ':' ) if ':' in target else ( target , None ) module = __import__ ( parts ) for part in parts . split ( '.' ) [ 1 : ] + ( [ target ] if target else [ ] ) : module = getattr ( module , part ) return module
This helper function loads an object identified by a dotted - notation string .
156
14
15,357
def getargspec ( obj ) : argnames , varargs , varkw , _defaults = None , None , None , None if inspect . isfunction ( obj ) or inspect . ismethod ( obj ) : argnames , varargs , varkw , _defaults = inspect . getargspec ( obj ) elif inspect . isclass ( obj ) : if inspect . ismethoddescriptor ( obj . __init__ ) : argnames , varargs , varkw , _defaults = [ ] , False , False , None else : argnames , varargs , varkw , _defaults = inspect . getargspec ( obj . __init__ ) elif hasattr ( obj , '__call__' ) : argnames , varargs , varkw , _defaults = inspect . getargspec ( obj . __call__ ) else : raise TypeError ( "Object not callable?" ) # Need test case to prove this is even possible. # if (argnames, varargs, varkw, defaults) is (None, None, None, None): # raise InspectionFailed() if argnames and argnames [ 0 ] == 'self' : del argnames [ 0 ] if _defaults is None : _defaults = [ ] defaults = dict ( ) else : # Create a mapping dictionary of defaults; this is slightly more useful. defaults = dict ( ) _defaults = list ( _defaults ) _defaults . reverse ( ) argnames . reverse ( ) for i , default in enumerate ( _defaults ) : defaults [ argnames [ i ] ] = default argnames . reverse ( ) # del argnames[-len(_defaults):] return argnames , defaults , True if varargs else False , True if varkw else False
An improved inspect . getargspec .
382
8
15,358
def get_queryset ( self ) : try : date = ElectionDay . objects . get ( date = self . kwargs [ "date" ] ) except Exception : raise APIException ( "No elections on {}." . format ( self . kwargs [ "date" ] ) ) division_ids = [ ] normal_elections = date . elections . filter ( ) if len ( normal_elections ) > 0 : for election in date . elections . all ( ) : if election . division . level . name == DivisionLevel . STATE : division_ids . append ( election . division . uid ) elif election . division . level . name == DivisionLevel . DISTRICT : division_ids . append ( election . division . parent . uid ) return Division . objects . filter ( uid__in = division_ids )
Returns a queryset of all states holding a non - special election on a date .
175
18
15,359
def get_relative_path ( self , domain , locale ) : return self . relative_path_template . format ( domain = domain , locale = locale , extension = self . get_extension ( ) )
Gets the relative file path using the template .
44
10
15,360
async def _overlap ( items , overlap_attr , client = None , get_method = None ) : overlap = set . intersection ( * ( getattr ( item , overlap_attr ) for item in items ) ) if client is None or get_method is None : return overlap results = [ ] for item in overlap : result = await getattr ( client , get_method ) ( id_ = item . id_ ) results . append ( result ) return results
Generic overlap implementation .
98
4
15,361
async def _find_overlap ( queries , client , find_method , get_method , overlap_function ) : results = [ ] for query in queries : candidates = await getattr ( client , find_method ) ( query ) if not candidates : raise ValueError ( 'no result found for {!r}' . format ( query ) ) result = await getattr ( client , get_method ) ( id_ = candidates [ 0 ] . id_ ) results . append ( result ) return await overlap_function ( results , client )
Generic find and overlap implementation .
114
6
15,362
def before ( self , context ) : run . before_each . execute ( context ) self . _invoke ( self . _before , context )
Invokes all before functions with context passed to them .
30
11
15,363
def after ( self , context ) : self . _invoke ( self . _after , context ) run . after_each . execute ( context )
Invokes all after functions with context passed to them .
30
11
15,364
def repr ( self , * args , * * kwargs ) : if not self . is_numpy : text = "'" + self . str ( * args , * * kwargs ) + "'" else : text = "{} numpy array, {} uncertainties" . format ( self . shape , len ( self . uncertainties ) ) return "<{} at {}, {}>" . format ( self . __class__ . __name__ , hex ( id ( self ) ) , text )
Returns the unique string representation of the number .
104
9
15,365
def get_states ( self , obj ) : return reverse ( 'electionnight_api_state-election-list' , request = self . context [ 'request' ] , kwargs = { 'date' : obj . date } )
States holding a non - special election on election day .
51
11
15,366
def get_bodies ( self , obj ) : return reverse ( 'electionnight_api_body-election-list' , request = self . context [ 'request' ] , kwargs = { 'date' : obj . date } )
Bodies with offices up for election on election day .
52
11
15,367
def get_executive_offices ( self , obj ) : return reverse ( 'electionnight_api_office-election-list' , request = self . context [ 'request' ] , kwargs = { 'date' : obj . date } )
Executive offices up for election on election day .
55
9
15,368
def get_special_elections ( self , obj ) : return reverse ( 'electionnight_api_special-election-list' , request = self . context [ 'request' ] , kwargs = { 'date' : obj . date } )
States holding a special election on election day .
54
9
15,369
def normalize ( arg = None ) : res = '' t_arg = type ( arg ) if t_arg in ( list , tuple ) : for i in arg : res += normalize ( i ) elif t_arg is dict : keys = arg . keys ( ) keys . sort ( ) for key in keys : res += '%s%s' % ( normalize ( key ) , normalize ( arg [ key ] ) ) elif t_arg is unicode : res = arg . encode ( 'utf8' ) elif t_arg is bool : res = 'true' if arg else 'false' elif arg != None : res = str ( arg ) return res
Normalizes an argument for signing purpose .
146
8
15,370
def sign ( shared_secret , msg ) : if isinstance ( msg , unicode ) : msg = msg . encode ( 'utf8' ) return hashlib . md5 ( msg + shared_secret ) . hexdigest ( )
Signs a message using a shared secret .
50
9
15,371
def config_parser_to_dict ( config_parser ) : response = { } for section in config_parser . sections ( ) : for option in config_parser . options ( section ) : response . setdefault ( section , { } ) [ option ] = config_parser . get ( section , option ) return response
Convert a ConfigParser to a dictionary .
67
9
15,372
def load_config_file ( config_file_path , config_file ) : if config_file_path . lower ( ) . endswith ( ".yaml" ) : return yaml . load ( config_file ) if any ( config_file_path . lower ( ) . endswith ( extension ) for extension in INI_FILE_EXTENSIONS ) : return load_config_from_ini_file ( config_file ) # At this point we have to guess the format of the configuration file. try : return yaml . load ( config_file ) except yaml . YAMLError : pass try : return load_config_from_ini_file ( config_file ) except : pass raise Exception ( "Could not load configuration file!" )
Loads a config file whether it is a yaml file or a . INI file .
165
19
15,373
def select ( keys , from_ , strict = False ) : ensure_iterable ( keys ) ensure_mapping ( from_ ) if strict : return from_ . __class__ ( ( k , from_ [ k ] ) for k in keys ) else : existing_keys = set ( keys ) & set ( iterkeys ( from_ ) ) return from_ . __class__ ( ( k , from_ [ k ] ) for k in existing_keys )
Selects a subset of given dictionary including only the specified keys .
97
13
15,374
def omit ( keys , from_ , strict = False ) : ensure_iterable ( keys ) ensure_mapping ( from_ ) if strict : remaining_keys = set ( iterkeys ( from_ ) ) remove_subset ( remaining_keys , keys ) # raises KeyError if necessary else : remaining_keys = set ( iterkeys ( from_ ) ) - set ( keys ) return from_ . __class__ ( ( k , from_ [ k ] ) for k in remaining_keys )
Returns a subset of given dictionary omitting specified keys .
105
11
15,375
def filteritems ( predicate , dict_ ) : predicate = all if predicate is None else ensure_callable ( predicate ) ensure_mapping ( dict_ ) return dict_ . __class__ ( ifilter ( predicate , iteritems ( dict_ ) ) )
Return a new dictionary comprising of items for which predicate returns True .
55
13
15,376
def starfilteritems ( predicate , dict_ ) : ensure_mapping ( dict_ ) if predicate is None : predicate = lambda k , v : all ( ( k , v ) ) else : ensure_callable ( predicate ) return dict_ . __class__ ( ( k , v ) for k , v in iteritems ( dict_ ) if predicate ( k , v ) )
Return a new dictionary comprising of keys and values for which predicate returns True .
80
15
15,377
def filterkeys ( predicate , dict_ ) : predicate = bool if predicate is None else ensure_callable ( predicate ) ensure_mapping ( dict_ ) return dict_ . __class__ ( ( k , v ) for k , v in iteritems ( dict_ ) if predicate ( k ) )
Return a new dictionary comprising of keys for which predicate returns True and their corresponding values .
63
17
15,378
def mapitems ( function , dict_ ) : ensure_mapping ( dict_ ) function = identity ( ) if function is None else ensure_callable ( function ) return dict_ . __class__ ( imap ( function , iteritems ( dict_ ) ) )
Return a new dictionary where the keys and values come from applying function to key - value pairs from given dictionary .
56
22
15,379
def starmapitems ( function , dict_ ) : ensure_mapping ( dict_ ) if function is None : function = lambda k , v : ( k , v ) else : ensure_callable ( function ) return dict_ . __class__ ( starmap ( function , iteritems ( dict_ ) ) )
Return a new dictionary where the keys and values come from applying function to the keys and values of given dictionary .
68
22
15,380
def mapkeys ( function , dict_ ) : ensure_mapping ( dict_ ) function = identity ( ) if function is None else ensure_callable ( function ) return dict_ . __class__ ( ( function ( k ) , v ) for k , v in iteritems ( dict_ ) )
Return a new dictionary where the keys come from applying function to the keys of given dictionary .
63
18
15,381
def merge ( * dicts , * * kwargs ) : ensure_argcount ( dicts , min_ = 1 ) dicts = list ( imap ( ensure_mapping , dicts ) ) ensure_keyword_args ( kwargs , optional = ( 'deep' , 'overwrite' ) ) return _nary_dict_update ( dicts , copy = True , deep = kwargs . get ( 'deep' , False ) , overwrite = kwargs . get ( 'overwrite' , True ) )
Merges two or more dictionaries into a single one .
115
12
15,382
def extend ( dict_ , * dicts , * * kwargs ) : ensure_mapping ( dict_ ) dicts = list ( imap ( ensure_mapping , dicts ) ) ensure_keyword_args ( kwargs , optional = ( 'deep' , 'overwrite' ) ) return _nary_dict_update ( [ dict_ ] + dicts , copy = False , deep = kwargs . get ( 'deep' , False ) , overwrite = kwargs . get ( 'overwrite' , True ) )
Extend a dictionary with keys and values from other dictionaries .
118
13
15,383
def _nary_dict_update ( dicts , * * kwargs ) : copy = kwargs [ 'copy' ] res = dicts [ 0 ] . copy ( ) if copy else dicts [ 0 ] if len ( dicts ) == 1 : return res # decide what strategy to use when updating a dictionary # with the values from another: {(non)recursive} x {(non)overwriting} deep = kwargs [ 'deep' ] overwrite = kwargs [ 'overwrite' ] if deep : dict_update = curry ( _recursive_dict_update , overwrite = overwrite ) else : if overwrite : dict_update = res . __class__ . update else : def dict_update ( dict_ , other ) : for k , v in iteritems ( other ) : dict_ . setdefault ( k , v ) for d in dicts [ 1 : ] : dict_update ( res , d ) return res
Implementation of n - argument dict . update with flags controlling the exact strategy .
203
16
15,384
def invert ( dict_ ) : ensure_mapping ( dict_ ) return dict_ . __class__ ( izip ( itervalues ( dict_ ) , iterkeys ( dict_ ) ) )
Return an inverted dictionary where former values are keys and former keys are values .
45
15
15,385
def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'first' , nargs = '?' ) parser . add_argument ( 'second' , nargs = '?' ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if not cmdargs . first : cmdargs . first = get_article ( ) else : if not check_article ( cmdargs . first ) : send ( "%s isn't a valid wikipedia article, fetching a random one..." % cmdargs . first ) cmdargs . first = get_article ( ) if not cmdargs . second : cmdargs . second = get_article ( ) else : if not check_article ( cmdargs . second ) : send ( "%s isn't a valid wikipedia article, fetching a random one..." % cmdargs . second ) cmdargs . second = get_article ( ) path = gen_path ( cmdargs ) if path : send ( path . replace ( '_' , ' ' ) ) else : send ( "No path found between %s and %s. Do you need to add more links?" % ( cmdargs . first . replace ( '_' , ' ' ) , cmdargs . second . replace ( '_' , ' ' ) ) )
Find a path between two wikipedia articles .
297
9
15,386
def remove_subset ( set_ , subset ) : ensure_set ( set_ ) ensure_iterable ( subset ) for elem in subset : set_ . remove ( elem )
Remove a subset from given set .
40
7
15,387
def power ( set_ ) : ensure_countable ( set_ ) result = chain . from_iterable ( combinations ( set_ , r ) for r in xrange ( len ( set_ ) + 1 ) ) return _harmonize_subset_types ( set_ , result )
Returns all subsets of given set .
62
8
15,388
def trivial_partition ( set_ ) : ensure_countable ( set_ ) result = ( ( x , ) for x in set_ ) return _harmonize_subset_types ( set_ , result )
Returns a parition of given set into 1 - element subsets .
47
14
15,389
def cmd ( send , msg , _ ) : demorse_codes = { '.----' : '1' , '-.--' : 'y' , '..-' : 'u' , '...' : 's' , '-.-.' : 'c' , '.-.-.' : '+' , '--..--' : ',' , '-.-' : 'k' , '.--.' : 'p' , '----.' : '9' , '-----' : '0' , ' ' : ' ' , '...--' : '3' , '-....-' : '-' , '...-..-' : '$' , '..---' : '2' , '.--.-.' : '@' , '-...-' : '=' , '-....' : '6' , '...-' : 'v' , '.----.' : "'" , '....' : 'h' , '.....' : '5' , '....-' : '4' , '.' : 'e' , '.-.-.-' : '.' , '-' : 't' , '.-..' : 'l' , '..' : 'i' , '.-' : 'a' , '-..-' : 'x' , '-...' : 'b' , '-.' : 'n' , '.-..-.' : '"' , '.--' : 'w' , '-.--.-' : ')' , '--...' : '7' , '.-.' : 'r' , '.---' : 'j' , '---..' : '8' , '--' : 'm' , '-.-.-.' : ';' , '-.-.--' : '!' , '-..' : 'd' , '-.--.' : '(' , '..-.' : 'f' , '---...' : ':' , '-..-.' : '/' , '..--.-' : '_' , '.-...' : '&' , '..--..' : '?' , '--.' : 'g' , '--..' : 'z' , '--.-' : 'q' , '---' : 'o' } demorse = "" if not msg : send ( "demorse what?" ) return for word in msg . lower ( ) . split ( " " ) : for c in word . split ( ) : if c in demorse_codes : demorse += demorse_codes [ c ] else : demorse += "?" demorse += " " send ( demorse )
Converts morse to ascii .
558
9
15,390
def cmd ( send , * _ ) : a = [ "primary" , "secondary" , "tertiary" , "hydraulic" , "compressed" , "required" , "pseudo" , "intangible" , "flux" ] b = [ "compressor" , "engine" , "lift" , "elevator" , "irc bot" , "stabilizer" , "computer" , "fwilson" , "csl" , "4506" , "router" , "switch" , "thingy" , "capacitor" ] c = [ "broke" , "exploded" , "corrupted" , "melted" , "froze" , "died" , "reset" , "was seen by the godofskies" , "burned" , "corroded" , "reversed polarity" , "was accidentallied" , "nuked" ] send ( "because %s %s %s" % ( ( choice ( a ) , choice ( b ) , choice ( c ) ) ) )
Gives a reason for something .
240
7
15,391
def cast ( type_ , value , default = ABSENT ) : # ``type_`` not being a type would theoretically be grounds for TypeError, # but since that kind of exception is a valid and expected outcome here # in some cases, we use the closest Python has to compilation error instead assert isinstance ( type_ , type ) # conunterintuitively, invalid conversions to numeric types # would raise ValueError rather than the more appropriate TypeError, # so we correct this inconsistency to_number = issubclass ( type_ , Number ) exception = ValueError if to_number else TypeError try : return type_ ( value ) except exception as e : if default is ABSENT : if to_number : # since Python 3 chains exceptions, we can supply slightly # more relevant error message while still retaining # the original information of ValueError as the cause msg = ( "cannot convert %r to %r" % ( value , type_ ) if IS_PY3 else str ( e ) ) raise TypeError ( msg ) else : raise return type_ ( default )
Cast a value to given type optionally returning a default if provided .
224
13
15,392
def is_identifier ( s ) : ensure_string ( s ) if not IDENTIFIER_FORM_RE . match ( s ) : return False if is_keyword ( s ) : return False # ``None`` is not part of ``keyword.kwlist`` in Python 2.x, # so we need to check for it explicitly if s == 'None' and not IS_PY3 : return False return True
Check whether given string is a valid Python identifier .
92
10
15,393
def normalize ( pw ) : pw_lower = pw . lower ( ) return '' . join ( helper . L33T . get ( c , c ) for c in pw_lower )
Lower case and change the symbols to closest characters
44
9
15,394
def qth_pw ( self , q ) : return heapq . nlargest ( q + 2 , self . _T . iteritems ( ) , key = operator . itemgetter ( 1 ) ) [ - 1 ]
returns the qth most probable element in the dawg .
48
14
15,395
def prob ( self , pw ) : tokens = self . pcfgtokensofw ( pw ) S , tokens = tokens [ 0 ] , tokens [ 1 : ] l = len ( tokens ) assert l % 2 == 0 , "Expecting even number of tokens!. got {}" . format ( tokens ) p = float ( self . _T . get ( S , 0.0 ) ) / sum ( v for k , v in self . _T . items ( '__S__' ) ) for i , t in enumerate ( tokens ) : f = self . _T . get ( t , 0.0 ) if f == 0 : return 0.0 if i < l / 2 : p /= f else : p *= f # print pw, p, t, self._T.get(t) return p
Return the probability of pw under the Weir PCFG model . P [ { S - > L2D1Y3 L2 - > ab D1 - > 1 Y3 - > !
178
40
15,396
def _get_next ( self , history ) : orig_history = history if not history : return helper . START history = history [ - ( self . _n - 1 ) : ] while history and not self . _T . get ( history ) : history = history [ 1 : ] kv = [ ( k , v ) for k , v in self . _T . items ( history ) if not ( k in reserved_words or k == history ) ] total = sum ( v for k , v in kv ) while total == 0 and len ( history ) > 0 : history = history [ 1 : ] kv = [ ( k , v ) for k , v in self . _T . items ( history ) if not ( k in reserved_words or k == history ) ] total = sum ( v for k , v in kv ) assert total > 0 , "Sorry there is no n-gram with {!r}" . format ( orig_history ) d = defaultdict ( float ) total = self . _T . get ( history ) for k , v in kv : k = k [ len ( history ) : ] d [ k ] += ( v + 1 ) / ( total + N_VALID_CHARS - 1 ) return d
Get the next set of characters and their probabilities
266
9
15,397
def _gen_next ( self , history ) : orig_history = history if not history : return helper . START history = history [ - ( self . _n - 1 ) : ] kv = [ ( k , v ) for k , v in self . _T . items ( history ) if k not in reserved_words ] total = sum ( v for k , v in kv ) while total == 0 and len ( history ) > 0 : history = history [ 1 : ] kv = [ ( k , v ) for k , v in self . _T . items ( history ) if k not in reserved_words ] total = sum ( v for k , v in kv ) assert total > 0 , "Sorry there is no n-gram with {!r}" . format ( orig_history ) _ , sampled_k = list ( helper . sample_following_dist ( kv , 1 , total ) ) [ 0 ] # print(">>>", repr(sampled_k), len(history)) return sampled_k [ len ( history ) ]
Generate next character sampled from the distribution of characters next .
225
12
15,398
def generate_pws_in_order ( self , n , filter_func = None , N_max = 1e6 ) : # assert alpha < beta, 'alpha={} must be less than beta={}'.format(alpha, beta) states = [ ( - 1.0 , helper . START ) ] # get the topk first p_min = 1e-9 / ( n ** 2 ) # max 1 million entries in the heap ret = [ ] done = set ( ) already_added_in_heap = set ( ) while len ( ret ) < n and len ( states ) > 0 : # while n > 0 and len(states) > 0: p , s = heapq . heappop ( states ) if p < 0 : p = - p if s in done : continue assert s [ 0 ] == helper . START , "Broken s: {!r}" . format ( s ) if s [ - 1 ] == helper . END : done . add ( s ) clean_s = s [ 1 : - 1 ] if filter_func is None or filter_func ( clean_s ) : ret . append ( ( clean_s , p ) ) # n -= 1 # yield (clean_s, p) else : for c , f in self . _get_next ( s ) . items ( ) : if ( f * p < p_min or ( s + c ) in done or ( s + c ) in already_added_in_heap ) : continue already_added_in_heap . add ( s + c ) heapq . heappush ( states , ( - f * p , s + c ) ) if len ( states ) > N_max * 3 / 2 : print ( "Heap size: {}. ret={}. (expected: {}) s={!r}" . format ( len ( states ) , len ( ret ) , n , s ) ) print ( "The size of states={}. Still need={} pws. Truncating" . format ( len ( states ) , n - len ( ret ) ) ) states = heapq . nsmallest ( int ( N_max * 3 / 4 ) , states ) print ( "Done" ) return ret
Generates passwords in order between upto N_max
476
11
15,399
def prob_correction ( self , f = 1 ) : total = { 'rockyou' : 32602160 } return f * self . _T [ TOTALF_W ] / total . get ( self . _leak , self . _T [ TOTALF_W ] )
Corrects the probability error due to truncating the distribution .
60
12