idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
15,400 | 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 . |
15,401 | def load_planet_list ( ) : planet_list = [ ] with open ( fldr + os . sep + 'planet_samples.csv' ) as f : hdr = f . readline ( ) for line in f : 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 |
15,402 | def create_character ( ) : traits = character . CharacterCollection ( character . fldr ) c = traits . generate_random_character ( ) print ( c ) return c | create a random character |
15,403 | 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 |
15,404 | def name_replace ( self , to_replace , replacement ) : self . name = self . name . replace ( to_replace , replacement ) | Replaces part of tag name with new value |
15,405 | 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 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 . |
15,406 | 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 . |
15,407 | 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 . |
15,408 | def cmd ( send , msg , args ) : result = args [ 'db' ] . query ( Urls ) . order_by ( func . random ( ) ) . first ( ) send ( "%s" % result . url ) | Reposts a url . |
15,409 | 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 . |
15,410 | 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 . |
15,411 | 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 . |
15,412 | 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 . |
15,413 | 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 . |
15,414 | 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 . |
15,415 | 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 |
15,416 | 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 . |
15,417 | 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 . |
15,418 | 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 . |
15,419 | 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?" ) if argnames and argnames [ 0 ] == 'self' : del argnames [ 0 ] if _defaults is None : _defaults = [ ] defaults = dict ( ) else : defaults = dict ( ) _defaults = list ( _defaults ) _defaults . reverse ( ) argnames . reverse ( ) for i , default in enumerate ( _defaults ) : defaults [ argnames [ i ] ] = default argnames . reverse ( ) return argnames , defaults , True if varargs else False , True if varkw else False | An improved inspect . getargspec . |
15,420 | 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 . |
15,421 | 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 . |
15,422 | 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 . |
15,423 | 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 . |
15,424 | def before ( self , context ) : "Invokes all before functions with context passed to them." run . before_each . execute ( context ) self . _invoke ( self . _before , context ) | Invokes all before functions with context passed to them . |
15,425 | def after ( self , context ) : "Invokes all after functions with context passed to them." self . _invoke ( self . _after , context ) run . after_each . execute ( context ) | Invokes all after functions with context passed to them . |
15,426 | 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 . |
15,427 | 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 . |
15,428 | 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 . |
15,429 | 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 . |
15,430 | 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 . |
15,431 | 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 . |
15,432 | 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 . |
15,433 | 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 . |
15,434 | 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 ) 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 . |
15,435 | 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 . |
15,436 | def omit ( keys , from_ , strict = False ) : ensure_iterable ( keys ) ensure_mapping ( from_ ) if strict : remaining_keys = set ( iterkeys ( from_ ) ) remove_subset ( remaining_keys , keys ) 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 . |
15,437 | 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 . |
15,438 | 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 . |
15,439 | 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 . |
15,440 | 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 . |
15,441 | 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 . |
15,442 | 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 . |
15,443 | 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 . |
15,444 | 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 . |
15,445 | def _nary_dict_update ( dicts , ** kwargs ) : copy = kwargs [ 'copy' ] res = dicts [ 0 ] . copy ( ) if copy else dicts [ 0 ] if len ( dicts ) == 1 : return res 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 . |
15,446 | 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 . |
15,447 | 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 . |
15,448 | def remove_subset ( set_ , subset ) : ensure_set ( set_ ) ensure_iterable ( subset ) for elem in subset : set_ . remove ( elem ) | Remove a subset from given set . |
15,449 | 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 . |
15,450 | 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 . |
15,451 | 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 . |
15,452 | 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 . |
15,453 | def cast ( type_ , value , default = ABSENT ) : assert isinstance ( type_ , type ) 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 : 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 . |
15,454 | def is_identifier ( s ) : ensure_string ( s ) if not IDENTIFIER_FORM_RE . match ( s ) : return False if is_keyword ( s ) : return False if s == 'None' and not IS_PY3 : return False return True | Check whether given string is a valid Python identifier . |
15,455 | 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 |
15,456 | 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 . |
15,457 | 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 return p | Return the probability of pw under the Weir PCFG model . P [ { S - > L2D1Y3 L2 - > ab D1 - > 1 Y3 - > ! |
15,458 | 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 |
15,459 | 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 ] return sampled_k [ len ( history ) ] | Generate next character sampled from the distribution of characters next . |
15,460 | def generate_pws_in_order ( self , n , filter_func = None , N_max = 1e6 ) : states = [ ( - 1.0 , helper . START ) ] p_min = 1e-9 / ( n ** 2 ) ret = [ ] done = set ( ) already_added_in_heap = set ( ) while len ( ret ) < n 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 ) ) 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 |
15,461 | 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 . |
15,462 | def serialisable ( cls , key , obj ) : if key . startswith ( '_Serialisable' . format ( cls . __name__ ) ) : return False if key in obj . __whitelist : return True if '__' in key : return False if key in obj . __blacklist : return False if callable ( getattr ( obj , key ) ) : return False if hasattr ( obj . __class__ , key ) : if isinstance ( getattr ( obj . __class__ , key ) , property ) : return False return True | Determines what can be serialised and what shouldn t |
15,463 | def normalise ( array ) : min_val = array . min ( ) max_val = array . max ( ) array_range = max_val - min_val if array_range == 0 : if min_val > 0 : return np . ones ( array . shape , dtype = np . float ) return np . zeros ( array . shape , dtype = np . float ) return ( array . astype ( np . float ) - min_val ) / array_range | Return array normalised such that all values are between 0 and 1 . |
15,464 | def reduce_stack ( array3D , z_function ) : xmax , ymax , _ = array3D . shape projection = np . zeros ( ( xmax , ymax ) , dtype = array3D . dtype ) for x in range ( xmax ) : for y in range ( ymax ) : projection [ x , y ] = z_function ( array3D [ x , y , : ] ) return projection | Return 2D array projection of the input 3D array . |
15,465 | def map_stack ( array3D , z_function ) : _ , _ , zdim = array3D . shape return np . dstack ( [ z_function ( array3D [ : , : , z ] ) for z in range ( zdim ) ] ) | Return 3D array where each z - slice has had the function applied to it . |
15,466 | def check_dtype ( array , allowed ) : if not hasattr ( allowed , "__iter__" ) : allowed = [ allowed , ] if array . dtype not in allowed : raise ( TypeError ( "Invalid dtype {}. Allowed dtype(s): {}" . format ( array . dtype , allowed ) ) ) | Raises TypeError if the array is not of an allowed dtype . |
15,467 | def handle_ctrlchan ( handler , msg , nick , send ) : with handler . db . session_scope ( ) as db : parser = init_parser ( send , handler , nick , db ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : err_str = r"invalid choice: .* \(choose from 'quote', 'help', 'chanserv', 'cs', 'disable', 'enable', 'guard', 'unguard', 'show', 'accept', 'reject'\)" if not re . match ( err_str , str ( e ) ) : send ( str ( e ) ) return cmdargs . func ( cmdargs ) | Handle the control channel . |
15,468 | def cmd ( send , msg , args ) : incidents = get_incidents ( args [ 'config' ] [ 'api' ] [ 'wmatakey' ] ) if not incidents : send ( "No incidents found. Sure you picked the right metro system?" ) return for t , i in incidents . items ( ) : send ( "%s:" % get_type ( t ) ) for desc in i : send ( desc ) | Provides Metro Info . |
15,469 | def page_location ( self ) : cycle = self . election_day . cycle . name if self . content_type . model_class ( ) == PageType : print ( self . content_object ) return self . content_object . page_location_template ( ) elif self . content_type . model_class ( ) == Division : if self . content_object . level . name == DivisionLevel . STATE : if self . special_election : path = os . path . join ( self . content_object . slug , "special-election" , self . election_day . special_election_datestring ( ) , ) else : path = self . content_object . slug else : path = "" else : if self . division . level . name == DivisionLevel . STATE : if not self . content_object . body : path = os . path . join ( self . division . slug , "governor" ) else : path = os . path . join ( self . division . slug , self . content_object . slug ) else : path = self . content_object . slug return ( os . sep + os . path . normpath ( os . path . join ( cycle , path ) ) + os . sep ) | Returns the published URL for page . |
15,470 | def _get_object ( self , name ) : clean_name = self . _clean_name ( name ) try : return self . driver . get_object ( self . bucket , clean_name ) except ObjectDoesNotExistError : return None | Get object by its name . Return None if object not found |
15,471 | def delete ( self , name ) : obj = self . _get_object ( name ) if obj : return self . driver . delete_object ( obj ) | Delete object on remote |
15,472 | def listdir ( self , path = '/' ) : container = self . _get_bucket ( ) objects = self . driver . list_container_objects ( container ) path = self . _clean_name ( path ) if not path . endswith ( '/' ) : path = "%s/" % path files = [ ] dirs = [ ] for o in objects : if path == '/' : if o . name . count ( '/' ) == 0 : files . append ( o . name ) elif o . name . count ( '/' ) == 1 : dir_name = o . name [ : o . name . index ( '/' ) ] if dir_name not in dirs : dirs . append ( dir_name ) elif o . name . startswith ( path ) : if o . name . count ( '/' ) <= path . count ( '/' ) : if o . name . endswith ( '_$folder$' ) : name = o . name [ : - 9 ] name = name [ len ( path ) : ] dirs . append ( name ) else : name = o . name [ len ( path ) : ] files . append ( name ) return ( dirs , files ) | Lists the contents of the specified path returning a 2 - tuple of lists ; the first item being directories the second item being files . |
15,473 | def name ( cls , func ) : cls . count = cls . count + 1 fpath = '{}_{}{}' . format ( cls . count , func . __name__ , cls . suffix ) if cls . directory : fpath = os . path . join ( cls . directory , fpath ) return fpath | Return auto generated file name . |
15,474 | def split_pattern ( self ) : patterns = [ ] for p in self . split_order : patterns . append ( '_{}%{}' . format ( p . capitalize ( ) , p ) ) return '' . join ( patterns ) | Pattern used to split the input file . |
15,475 | def pick_random_target ( self ) : start_x = math . floor ( self . grd . grid_height / 2 ) start_y = math . floor ( self . grd . grid_width / 2 ) min_dist_from_x = 3 min_dist_from_y = 5 move_random_x = randint ( 1 , math . floor ( self . grd . grid_height / 2 ) ) move_random_y = randint ( 1 , math . floor ( self . grd . grid_width / 2 ) ) x = start_x + move_random_x - min_dist_from_x y = start_y + move_random_y - min_dist_from_y return [ x , y ] | returns coords of a randomly generated starting position mostly over to the right hand side of the world |
15,476 | def expand_seed ( self , start_seed , num_iterations , val ) : self . grd . set_tile ( start_seed [ 0 ] , start_seed [ 1 ] , val ) cur_pos = [ start_seed [ 0 ] , start_seed [ 1 ] ] while num_iterations > 0 : num_iterations -= 1 for y in range ( cur_pos [ 0 ] - randint ( 0 , 2 ) , cur_pos [ 0 ] + randint ( 0 , 2 ) ) : for x in range ( cur_pos [ 1 ] - randint ( 0 , 2 ) , cur_pos [ 1 ] + randint ( 0 , 2 ) ) : if x < self . grd . grid_width and x >= 0 and y >= 0 and y < self . grd . grid_height : if self . grd . get_tile ( y , x ) != val : self . grd . set_tile ( y , x , TERRAIN_LAND ) num_iterations -= 1 new_x = cur_pos [ 0 ] + randint ( 0 , 3 ) - 2 new_y = cur_pos [ 1 ] + randint ( 0 , 3 ) - 2 if new_x > self . grd . grid_width - 1 : new_x = 0 if new_y > self . grd . grid_height - 1 : new_y = 0 if new_x < 0 : new_x = self . grd . grid_width - 1 if new_y < 0 : new_y = self . grd . grid_height - 1 cur_pos = [ new_y , new_x ] | takes a seed start point and grows out in random directions setting cell points to val |
15,477 | def denoise_grid ( self , val , expand = 1 ) : updated_grid = [ [ self . grd . get_tile ( y , x ) for x in range ( self . grd . grid_width ) ] for y in range ( self . grd . grid_height ) ] for row in range ( self . grd . get_grid_height ( ) - expand ) : for col in range ( self . grd . get_grid_width ( ) - expand ) : updated_grid [ row ] [ col ] = self . grd . get_tile ( row , col ) if self . grd . get_tile ( row , col ) == val : for y in range ( - expand , expand ) : for x in range ( - expand , expand ) : new_x = col + x new_y = row + y if new_x < 0 : new_x = 0 if new_y < 0 : new_y = 0 if new_x > self . grd . get_grid_width ( ) - 1 : new_x = self . grd . get_grid_width ( ) - 1 if new_y > self . grd . get_grid_height ( ) - 1 : new_y = self . grd . get_grid_height ( ) - 1 if expand > 0 : if randint ( 1 , expand * 2 ) > ( expand + 1 ) : updated_grid [ new_y ] [ new_x ] = val else : updated_grid [ new_y ] [ new_x ] = val self . grd . replace_grid ( updated_grid ) | for every cell in the grid of val fill all cells around it to de noise the grid |
15,478 | def add_mountains ( self ) : from noise import pnoise2 import random random . seed ( ) octaves = ( random . random ( ) * 0.5 ) + 0.5 freq = 17.0 * octaves for y in range ( self . grd . grid_height - 1 ) : for x in range ( self . grd . grid_width - 1 ) : pixel = self . grd . get_tile ( y , x ) if pixel == 'X' : n = int ( pnoise2 ( x / freq , y / freq , 1 ) * 11 + 5 ) if n < 1 : self . grd . set_tile ( y , x , '#' ) | instead of the add_blocks function which was to produce line shaped walls for blocking path finding agents this function creates more natural looking blocking areas like mountains |
15,479 | def add_block ( self ) : row_max = self . grd . get_grid_height ( ) - 15 if row_max < 2 : row_max = 2 row = randint ( 0 , row_max ) col_max = self . grd . get_grid_width ( ) - 10 if col_max < 2 : col_max = 2 col = randint ( 0 , col_max ) direction = randint ( 1 , 19 ) - 10 if direction > 0 : y_len = 10 * ( math . floor ( self . grd . get_grid_height ( ) / 120 ) + 1 ) x_len = 1 * ( math . floor ( self . grd . get_grid_width ( ) / 200 ) + 1 ) else : y_len = 1 * ( math . floor ( self . grd . get_grid_height ( ) / 200 ) + 1 ) x_len = 10 * ( math . floor ( self . grd . get_grid_width ( ) / 120 ) + 1 ) print ( "Adding block to " , row , col , direction ) for r in range ( row , row + y_len ) : for c in range ( col , col + x_len ) : self . grd . set_tile ( r , c , TERRAIN_BLOCKED ) | adds a random size block to the map |
15,480 | def run ( self , num_runs , show_trails , log_file_base ) : print ( "--------------------------------------------------" ) print ( "Starting Simulation - target = " , self . agent_list [ 0 ] . target_y , self . agent_list [ 0 ] . target_x ) self . world . grd . set_tile ( self . agent_list [ 0 ] . target_y , self . agent_list [ 0 ] . target_x , 'T' ) self . highlight_cell_surroundings ( self . agent_list [ 0 ] . target_y , self . agent_list [ 0 ] . target_x ) self . start_all_agents ( ) try : with open ( log_file_base + '__agents.txt' , "w" ) as f : f . write ( "Starting World = \n" ) f . write ( str ( self . world . grd ) ) except Exception : print ( 'Cant save log results to ' + log_file_base ) for cur_run in range ( 0 , num_runs ) : print ( "WorldSimulation:run#" , cur_run ) for num , agt in enumerate ( self . agent_list ) : if show_trails == 'Y' : if len ( self . agent_list ) == 1 or len ( self . agent_list ) > 9 : self . world . grd . set_tile ( agt . current_y , agt . current_x , 'o' ) else : self . world . grd . set_tile ( agt . current_y , agt . current_x , str ( num ) ) agt . do_your_job ( ) self . world . grd . set_tile ( agt . current_y , agt . current_x , 'A' ) if log_file_base != 'N' : self . world . grd . save ( log_file_base + '_' + str ( cur_run ) + '.log' ) with open ( log_file_base + '__agents.txt' , "a" ) as f : f . write ( "\nWorld tgt= [" + str ( self . agent_list [ 0 ] . target_y ) + "," + str ( self . agent_list [ 0 ] . target_x ) + "]\n" ) f . write ( str ( self . world . grd ) ) f . write ( '\n\nAgent Name , starting, num Steps , num Climbs\n' ) for num , agt in enumerate ( self . agent_list ) : res = agt . name + ' , [' + str ( agt . start_y ) + ', ' + str ( agt . start_x ) + '], ' res += str ( agt . num_steps ) + ' , ' + str ( agt . num_climbs ) + ' , ' res += '' . join ( [ a for a in agt . results ] ) f . write ( res + '\n' ) | Run each agent in the world for num_runs iterations Optionally saves grid results to file if base name is passed to method . |
15,481 | def highlight_cell_surroundings ( self , target_y , target_x ) : if target_y < 1 : print ( "target too close to top" ) if target_y > self . world . grd . grid_height - 1 : print ( "target too close to bottom" ) if target_x < 1 : print ( "target too close to left" ) if target_x < self . world . grd . grid_width : print ( "target too close to right" ) self . world . grd . set_tile ( target_y - 1 , target_x - 1 , '\\' ) self . world . grd . set_tile ( target_y - 0 , target_x - 1 , '-' ) self . world . grd . set_tile ( target_y + 1 , target_x - 1 , '/' ) self . world . grd . set_tile ( target_y - 1 , target_x - 0 , '|' ) self . world . grd . set_tile ( target_y + 1 , target_x - 0 , '|' ) self . world . grd . set_tile ( target_y - 1 , target_x + 1 , '/' ) self . world . grd . set_tile ( target_y - 0 , target_x + 1 , '-' ) self . world . grd . set_tile ( target_y + 1 , target_x + 1 , '\\' ) | highlights the cells around a target to make it simpler to see on a grid . Currently assumes the target is within the boundary by 1 on all sides |
15,482 | def cmd ( send , _ , args ) : def lenny_send ( msg ) : send ( gen_lenny ( msg ) ) key = args [ 'config' ] [ 'api' ] [ 'bitlykey' ] cmds = [ lambda : gen_fortune ( lenny_send ) , lambda : gen_urban ( lenny_send , args [ 'db' ] , key ) ] choice ( cmds ) ( ) | Abuses the bot . |
15,483 | def hamming_distance ( s1 , s2 ) : if len ( s1 ) != len ( s2 ) : raise ValueError ( "Undefined for sequences of unequal length" ) return sum ( el1 != el2 for el1 , el2 in zip ( s1 . upper ( ) , s2 . upper ( ) ) ) | Return the Hamming distance between equal - length sequences |
15,484 | def cmd ( send , msg , args ) : if not msg : send ( "Explain What?" ) return msg = msg . replace ( ' ' , '+' ) msg = 'http://lmgtfy.com/?q=%s' % msg key = args [ 'config' ] [ 'api' ] [ 'bitlykey' ] send ( get_short ( msg , key ) ) | Explain things . |
15,485 | def split_msg ( msgs : List [ bytes ] , max_len : int ) -> Tuple [ str , List [ bytes ] ] : msg = "" while len ( msg . encode ( ) ) < max_len : if len ( msg . encode ( ) ) + len ( msgs [ 0 ] ) > max_len : return msg , msgs char = msgs . pop ( 0 ) . decode ( ) if char == " " and len ( msg . encode ( ) ) > max_len - 15 : return msg , msgs msg += char return msg , msgs | Splits as close to the end as possible . |
15,486 | def check ( self , order , sids ) : payload = "{}" raw_msg = self . client . blpop ( self . channel , timeout = self . timeout ) if raw_msg : _ , payload = raw_msg msg = json . loads ( payload . replace ( "'" , '"' ) , encoding = 'utf-8' ) for sid in msg . keys ( ) : if sid . lower ( ) in map ( str . lower , sids ) : print ( 'ordering {} of {}' . format ( msg [ sid ] , sid ) ) order ( sid , msg [ sid ] ) else : print ( 'skipping unknown symbol {}' . format ( sid ) ) | Check if a message is available |
15,487 | def cmd ( send , msg , args ) : if not msg : send ( "This tastes yummy!" ) elif msg == args [ 'botnick' ] : send ( "wyang says Cannibalism is generally frowned upon." ) else : send ( "%s tastes yummy!" % msg . capitalize ( ) ) | Causes the bot to snack on something . |
15,488 | def next ( self ) : if not self . _cache : self . _cache = self . _get_results ( ) self . _retrieved += len ( self . _cache ) if not self . _cache : raise StopIteration ( ) return self . _cache . pop ( 0 ) | Provide iteration capabilities |
15,489 | def cmd ( send , msg , args ) : users = get_users ( args ) if " into " in msg and msg != "into" : match = re . match ( '(.*) into (.*)' , msg ) if match : msg = 'throws %s into %s' % ( match . group ( 1 ) , match . group ( 2 ) ) send ( msg , 'action' ) else : return elif " at " in msg and msg != "at" : match = re . match ( '(.*) at (.*)' , msg ) if match : msg = 'throws %s at %s' % ( match . group ( 1 ) , match . group ( 2 ) ) send ( msg , 'action' ) else : return elif msg : msg = 'throws %s at %s' % ( msg , choice ( users ) ) send ( msg , 'action' ) else : send ( "Throw what?" ) return | Throw something . |
15,490 | def wrap ( self , function ) : func = inspect . getfullargspec ( function ) needed_arguments = func . args + func . kwonlyargs @ wraps ( function ) def wrapper ( * args , ** kwargs ) : arguments = kwargs . copy ( ) missing_arguments = needed_arguments - arguments . keys ( ) for arg in missing_arguments : try : arguments [ arg ] = self . _get_argument ( arg ) except KeyError : pass return function ( * args , ** arguments ) return wrapper | Wraps a function so that all unspecified arguments will be injected if possible . Specified arguments always have precedence . |
15,491 | def call ( self , func , * args , ** kwargs ) : wrapped = self . wrap ( func ) return wrapped ( * args , ** kwargs ) | Calls a specified function using the provided arguments and injectable arguments . |
15,492 | def png ( self ) : use_plugin ( 'freeimage' ) with TemporaryFilePath ( suffix = '.png' ) as tmp : safe_range_im = 255 * normalise ( self ) imsave ( tmp . fpath , safe_range_im . astype ( np . uint8 ) ) with open ( tmp . fpath , 'rb' ) as fh : return fh . read ( ) | Return png string of image . |
15,493 | def is_me ( self , s , c , z , t ) : if ( self . series == s and self . channel == c and self . zslice == z and self . timepoint == t ) : return True return False | Return True if arguments match my meta data . |
15,494 | def in_zstack ( self , s , c , t ) : if ( self . series == s and self . channel == c and self . timepoint == t ) : return True return False | Return True if I am in the zstack . |
15,495 | def find_specs ( self , directory ) : specs = [ ] spec_files = self . file_finder . find ( directory ) for spec_file in spec_files : specs . extend ( self . spec_finder . find ( spec_file . module ) ) return specs | Finds all specs in a given directory . Returns a list of Example and ExampleGroup instances . |
15,496 | def flip ( f ) : ensure_callable ( f ) result = lambda * args , ** kwargs : f ( * reversed ( args ) , ** kwargs ) functools . update_wrapper ( result , f , ( '__name__' , '__module__' ) ) return result | Flip the order of positonal arguments of given function . |
15,497 | def compose ( * fs ) : ensure_argcount ( fs , min_ = 1 ) fs = list ( imap ( ensure_callable , fs ) ) if len ( fs ) == 1 : return fs [ 0 ] if len ( fs ) == 2 : f1 , f2 = fs return lambda * args , ** kwargs : f1 ( f2 ( * args , ** kwargs ) ) if len ( fs ) == 3 : f1 , f2 , f3 = fs return lambda * args , ** kwargs : f1 ( f2 ( f3 ( * args , ** kwargs ) ) ) fs . reverse ( ) def g ( * args , ** kwargs ) : x = fs [ 0 ] ( * args , ** kwargs ) for f in fs [ 1 : ] : x = f ( x ) return x return g | Creates composition of the functions passed in . |
15,498 | def merge ( arg , * rest , ** kwargs ) : ensure_keyword_args ( kwargs , optional = ( 'default' , ) ) has_default = 'default' in kwargs if has_default : default = ensure_callable ( kwargs [ 'default' ] ) unary_result = True if rest : fs = ( ensure_callable ( arg ) , ) + tuple ( imap ( ensure_callable , rest ) ) unary_result = False else : fs = arg if is_mapping ( fs ) : if has_default : return lambda arg_ : fs . __class__ ( ( k , fs . get ( k , default ) ( arg_ [ k ] ) ) for k in arg_ ) else : return lambda arg_ : fs . __class__ ( ( k , fs [ k ] ( arg_ [ k ] ) ) for k in arg_ ) else : ensure_sequence ( fs ) if has_default : func = lambda arg_ : fs . __class__ ( ( fs [ i ] if i < len ( fs ) else default ) ( x ) for i , x in enumerate ( arg_ ) ) else : func = lambda arg_ : fs . __class__ ( fs [ i ] ( x ) for i , x in enumerate ( arg_ ) ) return func if unary_result else lambda * args : func ( args ) | Merge a collection with functions as items into a single function that takes a collection and maps its items through corresponding functions . |
15,499 | def and_ ( * fs ) : ensure_argcount ( fs , min_ = 1 ) fs = list ( imap ( ensure_callable , fs ) ) if len ( fs ) == 1 : return fs [ 0 ] if len ( fs ) == 2 : f1 , f2 = fs return lambda * args , ** kwargs : ( f1 ( * args , ** kwargs ) and f2 ( * args , ** kwargs ) ) if len ( fs ) == 3 : f1 , f2 , f3 = fs return lambda * args , ** kwargs : ( f1 ( * args , ** kwargs ) and f2 ( * args , ** kwargs ) and f3 ( * args , ** kwargs ) ) def g ( * args , ** kwargs ) : for f in fs : if not f ( * args , ** kwargs ) : return False return True return g | Creates a function that returns true for given arguments iff every given function evalutes to true for those arguments . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.