idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
15,000 | def strategy ( self ) : 'Returns resulting strategy that generates configured char set' max_codepoint = None if self . _unicode else 127 strategies = [ ] if self . _negate : if self . _categories or self . _whitelist_chars : strategies . append ( hs . characters ( blacklist_categories = self . _categories | set ( [ 'Cc' , 'Cs' ] ) , blacklist_characters = self . _whitelist_chars , max_codepoint = max_codepoint , ) ) if self . _blacklist_chars : strategies . append ( hs . sampled_from ( list ( self . _blacklist_chars - self . _whitelist_chars ) ) ) else : if self . _categories or self . _blacklist_chars : strategies . append ( hs . characters ( whitelist_categories = self . _categories , blacklist_characters = self . _blacklist_chars , max_codepoint = max_codepoint , ) ) if self . _whitelist_chars : strategies . append ( hs . sampled_from ( list ( self . _whitelist_chars - self . _blacklist_chars ) ) ) return hs . one_of ( * strategies ) if strategies else hs . just ( u'' ) | Returns resulting strategy that generates configured char set |
15,001 | def add_category ( self , category ) : if category == sre . CATEGORY_DIGIT : self . _categories |= UNICODE_DIGIT_CATEGORIES elif category == sre . CATEGORY_NOT_DIGIT : self . _categories |= UNICODE_CATEGORIES - UNICODE_DIGIT_CATEGORIES elif category == sre . CATEGORY_SPACE : self . _categories |= UNICODE_SPACE_CATEGORIES for c in ( UNICODE_SPACE_CHARS if self . _unicode else SPACE_CHARS ) : self . _whitelist_chars . add ( c ) elif category == sre . CATEGORY_NOT_SPACE : self . _categories |= UNICODE_CATEGORIES - UNICODE_SPACE_CATEGORIES for c in ( UNICODE_SPACE_CHARS if self . _unicode else SPACE_CHARS ) : self . _blacklist_chars . add ( c ) elif category == sre . CATEGORY_WORD : self . _categories |= UNICODE_WORD_CATEGORIES self . _whitelist_chars . add ( u'_' ) if HAS_WEIRD_WORD_CHARS and self . _unicode : for c in UNICODE_WEIRD_NONWORD_CHARS : self . _blacklist_chars . add ( c ) elif category == sre . CATEGORY_NOT_WORD : self . _categories |= UNICODE_CATEGORIES - UNICODE_WORD_CATEGORIES self . _blacklist_chars . add ( u'_' ) if HAS_WEIRD_WORD_CHARS and self . _unicode : for c in UNICODE_WEIRD_NONWORD_CHARS : self . _whitelist_chars . add ( c ) | Add unicode category to set |
15,002 | def add_chars ( self , chars ) : 'Add given chars to char set' for c in chars : if self . _ignorecase : self . _whitelist_chars . add ( c . lower ( ) ) self . _whitelist_chars . add ( c . upper ( ) ) else : self . _whitelist_chars . add ( c ) | Add given chars to char set |
15,003 | def str_traceback ( error , tb ) : if not isinstance ( tb , types . TracebackType ) : return tb return '' . join ( traceback . format_exception ( error . __class__ , error , tb ) ) | Returns a string representation of the traceback . |
15,004 | def filter_traceback ( error , tb , ignore_pkg = CURRENT_PACKAGE ) : if not isinstance ( tb , types . TracebackType ) : return tb def in_namespace ( n ) : return n and ( n . startswith ( ignore_pkg + '.' ) or n == ignore_pkg ) while tb and in_namespace ( tb . tb_frame . f_globals [ '__package__' ] ) : tb = tb . tb_next starting_tb = tb limit = 0 while tb and not in_namespace ( tb . tb_frame . f_globals [ '__package__' ] ) : tb = tb . tb_next limit += 1 return '' . join ( traceback . format_exception ( error . __class__ , error , starting_tb , limit ) ) | Filtered out all parent stacktraces starting with the given stacktrace that has a given variable name in its globals . |
15,005 | def get_true_function ( obj ) : "Returns the actual function and a boolean indicated if this is a method or not." if not callable ( obj ) : raise TypeError ( "%r is not callable." % ( obj , ) ) ismethod = inspect . ismethod ( obj ) if inspect . isfunction ( obj ) or ismethod : return obj , ismethod if hasattr ( obj , 'im_func' ) : return obj . im_func , True if inspect . isclass ( obj ) : return getattr ( obj , '__init__' , None ) , True if isinstance ( obj , object ) : if hasattr ( obj , 'func' ) : return get_true_function ( obj . func ) return obj . __call__ , True raise TypeError ( "Unknown type of object: %r" % obj ) | Returns the actual function and a boolean indicated if this is a method or not . |
15,006 | def assert_valid_path ( self , path ) : if not isinstance ( path , str ) : raise NotFoundResourceException ( "Resource passed to load() method must be a file path" ) if not os . path . isfile ( path ) : raise NotFoundResourceException ( 'File "{0}" does not exist' . format ( path ) ) | Ensures that the path represents an existing file |
15,007 | def read_file ( self , path ) : self . assert_valid_path ( path ) with open ( path , 'rb' ) as file : contents = file . read ( ) . decode ( 'UTF-8' ) return contents | Reads a file into memory and returns it s contents |
15,008 | def flatten ( self , messages , parent_key = '' ) : items = [ ] sep = '.' for k , v in list ( messages . items ( ) ) : new_key = "{0}{1}{2}" . format ( parent_key , sep , k ) if parent_key else k if isinstance ( v , collections . MutableMapping ) : items . extend ( list ( self . flatten ( v , new_key ) . items ( ) ) ) else : items . append ( ( new_key , v ) ) return dict ( items ) | Flattens an nested array of translations . |
15,009 | def parse ( self , resource ) : try : import polib except ImportError as e : self . rethrow ( "You need to install polib to use PoFileLoader or MoFileLoader" , ImportError ) self . assert_valid_path ( resource ) messages = { } parsed = self . _load_contents ( polib , resource ) for item in parsed : if item . msgid_plural : plurals = sorted ( item . msgstr_plural . items ( ) ) if item . msgid and len ( plurals ) > 1 : messages [ item . msgid ] = plurals [ 0 ] [ 1 ] plurals = [ msgstr for idx , msgstr in plurals ] messages [ item . msgid_plural ] = "|" . join ( plurals ) elif item . msgid : messages [ item . msgid ] = item . msgstr return messages | Loads given resource into a dict using polib |
15,010 | def arch ( self ) : if self . method in ( 'buildArch' , 'createdistrepo' , 'livecd' ) : return self . params [ 2 ] if self . method in ( 'createrepo' , 'runroot' ) : return self . params [ 1 ] if self . method == 'createImage' : return self . params [ 3 ] if self . method == 'indirectionimage' : return self . params [ 0 ] [ 'arch' ] | Return an architecture for this task . |
15,011 | def arches ( self ) : if self . method == 'image' : return self . params [ 2 ] if self . arch : return [ self . arch ] return [ ] | Return a list of architectures for this task . |
15,012 | def duration ( self ) : if not self . started : return None start = self . started end = self . completed if not end : end = datetime . utcnow ( ) return end - start | Return a timedelta for this task . |
15,013 | def estimate_completion ( self ) : if self . completion_ts : defer . returnValue ( self . completed ) if self . method == 'build' or self . method == 'image' : subtask_completion = yield self . estimate_descendents ( ) defer . returnValue ( subtask_completion ) if self . state == task_states . FREE : est_completion = yield self . _estimate_free ( ) defer . returnValue ( est_completion ) avg_delta = yield self . estimate_duration ( ) if avg_delta is None : defer . returnValue ( None ) est_completion = self . started + avg_delta defer . returnValue ( est_completion ) | Estimate completion time for a task . |
15,014 | def _estimate_free ( self ) : capacity_deferred = self . channel . total_capacity ( ) open_tasks_deferred = self . channel . tasks ( state = [ task_states . OPEN ] ) avg_delta_deferred = self . estimate_duration ( ) deferreds = [ capacity_deferred , open_tasks_deferred , avg_delta_deferred ] results = yield defer . gatherResults ( deferreds , consumeErrors = True ) capacity , open_tasks , avg_delta = results open_weight = sum ( [ task . weight for task in open_tasks ] ) if open_weight >= capacity : raise NotImplementedError ( 'channel %d is at capacity' % self . channel_id ) start_time = self . created + SLEEPTIME if avg_delta is None : defer . returnValue ( None ) est_completion = start_time + avg_delta defer . returnValue ( est_completion ) | Estimate completion time for a free task . |
15,015 | def package ( self ) : if self . method == 'buildNotification' : return self . params [ 1 ] [ 'name' ] if self . method in ( 'createImage' , 'image' , 'livecd' ) : return self . params [ 0 ] if self . method == 'indirectionimage' : return self . params [ 0 ] [ 'name' ] if self . method not in ( 'build' , 'buildArch' , 'buildContainer' , 'buildMaven' , 'buildSRPMFromSCM' , 'maven' ) : return None source = self . params [ 0 ] o = urlparse ( source ) if source . endswith ( '.src.rpm' ) : srpm = os . path . basename ( source ) ( name , version , release ) = srpm . rsplit ( '-' , 2 ) return name elif o . scheme : package = os . path . basename ( o . path ) if package . endswith ( '.git' ) : package = package [ : - 4 ] if self . method == 'buildContainer' : package += '-container' return package raise ValueError ( 'could not parse source "%s"' % source ) | Find a package name from a build task s parameters . |
15,016 | def params ( self ) : if isinstance ( self . request , list ) : return unmunchify ( self . request ) ( params , _ ) = xmlrpc . loads ( self . request ) return params | Return a list of parameters in this task s request . |
15,017 | def cmd ( send , _ , args ) : try : if exists ( join ( args [ 'handler' ] . confdir , '.git' ) ) : send ( do_pull ( srcdir = args [ 'handler' ] . confdir ) ) else : send ( do_pull ( repo = args [ 'config' ] [ 'api' ] [ 'githubrepo' ] ) ) except subprocess . CalledProcessError as ex : for line in ex . output . strip ( ) . splitlines ( ) : logging . error ( line ) raise ex | Pull changes . |
15,018 | def _start_date_of_year ( year : int ) -> datetime . date : jan_one = datetime . date ( year , 1 , 1 ) diff = 7 * ( jan_one . isoweekday ( ) > 3 ) - jan_one . isoweekday ( ) return jan_one + datetime . timedelta ( days = diff ) | Return start date of the year using MMWR week rules |
15,019 | def date_to_epiweek ( date = datetime . date . today ( ) ) -> Epiweek : year = date . year start_dates = list ( map ( _start_date_of_year , [ year - 1 , year , year + 1 ] ) ) start_date = start_dates [ 1 ] if start_dates [ 1 ] > date : start_date = start_dates [ 0 ] elif date >= start_dates [ 2 ] : start_date = start_dates [ 2 ] return Epiweek ( year = ( start_date + datetime . timedelta ( days = 7 ) ) . year , week = ( ( date - start_date ) . days // 7 ) + 1 , day = ( date . isoweekday ( ) % 7 ) + 1 ) | Convert python date to Epiweek |
15,020 | def epiweeks_in_year ( year : int ) -> int : if date_to_epiweek ( epiweek_to_date ( Epiweek ( year , 53 ) ) ) . year == year : return 53 else : return 52 | Return number of epiweeks in a year |
15,021 | def parser ( self ) : if self . _command_parser is None : parents = [ ] if self . need_verbose : parents . append ( _verbose_parser ) if self . need_settings : parents . append ( _settings_parser ) self . _command_parser = self . _main_parser . add_parser ( self . name , help = self . help , parents = parents , formatter_class = argparse . RawDescriptionHelpFormatter ) return self . _command_parser | Returns the appropriate parser to use for adding arguments to your command . |
15,022 | def cmd ( send , _ , args ) : adminlist = [ ] for admin in args [ 'db' ] . query ( Permissions ) . order_by ( Permissions . nick ) . all ( ) : if admin . registered : adminlist . append ( "%s (V)" % admin . nick ) else : adminlist . append ( "%s (U)" % admin . nick ) send ( ", " . join ( adminlist ) , target = args [ 'nick' ] ) | Returns a list of admins . |
15,023 | def run ( self ) : x , y = 1 , 0 num_steps = 0 while self . s . get_state ( ) != 'Halted' : self . s . command ( { 'name' : 'walk' , 'type' : 'move' , 'direction' : [ x , y ] } , self . a1 ) self . s . command ( { 'name' : 'walk' , 'type' : 'run' , 'direction' : [ x , y + 1 ] } , self . a2 ) num_steps += 1 if num_steps >= 3 : break for a in self . s . agents : print ( a . name , 'finished at position ' , a . coords [ 'x' ] , a . coords [ 'y' ] ) | This AI simple moves the characters towards the opposite edges of the grid for 3 steps or until event halts the simulation |
15,024 | def validate ( schema_file , config_file , deprecation ) : result = validator_from_config_file ( config_file , schema_file ) result . validate ( error_on_deprecated = deprecation ) for error in result . errors ( ) : click . secho ( 'Error : %s' % error , err = True , fg = 'red' ) for warning in result . warnings ( ) : click . secho ( 'Warning : %s' % warning , err = True , fg = 'yellow' ) | Validate a configuration file against a confirm schema . |
15,025 | def migrate ( schema_file , config_file ) : schema = load_schema_file ( open ( schema_file , 'r' ) ) config = load_config_file ( config_file , open ( config_file , 'r' ) . read ( ) ) config = append_existing_values ( schema , config ) migrated_config = generate_config_parser ( config ) migrated_config . write ( sys . stdout ) | Migrates a configuration file using a confirm schema . |
15,026 | def document ( schema_file ) : schema = load_schema_file ( open ( schema_file , 'r' ) ) documentation = generate_documentation ( schema ) sys . stdout . write ( documentation ) | Generate reStructuredText documentation from a confirm schema . |
15,027 | def generate ( schema_file , all_options ) : schema = load_schema_file ( open ( schema_file , 'r' ) ) config_parser = generate_config_parser ( schema , include_all = all_options ) config_parser . write ( sys . stdout ) | Generates a template configuration file from a confirm schema . |
15,028 | def init ( config_file ) : schema = generate_schema_file ( open ( config_file , 'r' ) . read ( ) ) sys . stdout . write ( schema ) | Initialize a confirm schema from an existing configuration file . |
15,029 | def _init_random_gaussians ( self , X ) : n_samples = np . shape ( X ) [ 0 ] self . priors = ( 1 / self . k ) * np . ones ( self . k ) for _ in range ( self . k ) : params = { } params [ "mean" ] = X [ np . random . choice ( range ( n_samples ) ) ] params [ "cov" ] = calculate_covariance_matrix ( X ) self . parameters . append ( params ) | Initialize gaussian randomly |
15,030 | def _get_likelihoods ( self , X ) : n_samples = np . shape ( X ) [ 0 ] likelihoods = np . zeros ( ( n_samples , self . k ) ) for i in range ( self . k ) : likelihoods [ : , i ] = self . multivariate_gaussian ( X , self . parameters [ i ] ) return likelihoods | Calculate the likelihood over all samples |
15,031 | def _expectation ( self , X ) : weighted_likelihoods = self . _get_likelihoods ( X ) * self . priors sum_likelihoods = np . expand_dims ( np . sum ( weighted_likelihoods , axis = 1 ) , axis = 1 ) self . responsibility = weighted_likelihoods / sum_likelihoods self . sample_assignments = self . responsibility . argmax ( axis = 1 ) self . responsibilities . append ( np . max ( self . responsibility , axis = 1 ) ) | Calculate the responsibility |
15,032 | def _maximization ( self , X ) : for i in range ( self . k ) : resp = np . expand_dims ( self . responsibility [ : , i ] , axis = 1 ) mean = ( resp * X ) . sum ( axis = 0 ) / resp . sum ( ) covariance = ( X - mean ) . T . dot ( ( X - mean ) * resp ) / resp . sum ( ) self . parameters [ i ] [ "mean" ] , self . parameters [ i ] [ "cov" ] = mean , covariance n_samples = np . shape ( X ) [ 0 ] self . priors = self . responsibility . sum ( axis = 0 ) / n_samples | Update the parameters and priors |
15,033 | def _converged ( self , X ) : if len ( self . responsibilities ) < 2 : return False diff = np . linalg . norm ( self . responsibilities [ - 1 ] - self . responsibilities [ - 2 ] ) return diff <= self . tolerance | Covergence if || likehood - last_likelihood || < tolerance |
15,034 | def cluster ( self , X ) : self . _init_random_gaussians ( X ) for _ in range ( self . max_iterations ) : self . _expectation ( X ) self . _maximization ( X ) if self . _converged ( X ) : break self . _expectation ( X ) return self . sample_assignments | Run GMM and return the cluster indices |
15,035 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--lang' , '--from' , default = None ) parser . add_argument ( '--to' , default = 'en' ) parser . add_argument ( 'msg' , nargs = '+' ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return send ( gen_translate ( ' ' . join ( cmdargs . msg ) , cmdargs . lang , cmdargs . to ) ) | Translate something . |
15,036 | def cmd ( send , msg , _ ) : coin = [ 'heads' , 'tails' ] if not msg : send ( 'The coin lands on... %s' % choice ( coin ) ) elif not msg . lstrip ( '-' ) . isdigit ( ) : send ( "Not A Valid Positive Integer." ) else : msg = int ( msg ) if msg < 0 : send ( "Negative Flipping requires the (optional) quantum coprocessor." ) return headflips = randint ( 0 , msg ) tailflips = msg - headflips send ( 'The coins land on heads %g times and on tails %g times.' % ( headflips , tailflips ) ) | Flips a coin a number of times . |
15,037 | def is_admin ( self , send , nick , required_role = 'admin' ) : if not required_role : return True with self . db . session_scope ( ) as session : admin = session . query ( orm . Permissions ) . filter ( orm . Permissions . nick == nick ) . first ( ) if admin is None : return False if required_role == "owner" and admin . role != "owner" : return False if not self . config [ 'feature' ] . getboolean ( 'nickserv' ) : return True if not admin . registered : self . update_authstatus ( nick ) if send is not None : send ( "Unverified admin: %s" % nick , target = self . config [ 'core' ] [ 'channel' ] ) return False else : if not self . features [ 'account-notify' ] : if datetime . now ( ) - admin . time > timedelta ( minutes = 5 ) : self . update_authstatus ( nick ) return True | Checks if a nick is a admin . |
15,038 | def get_admins ( self ) : if not self . config [ 'feature' ] . getboolean ( 'nickserv' ) : return with self . db . session_scope ( ) as session : for a in session . query ( orm . Permissions ) . all ( ) : if not a . registered : self . update_authstatus ( a . nick ) | Check verification for all admins . |
15,039 | def abusecheck ( self , send , nick , target , limit , cmd ) : if nick not in self . abuselist : self . abuselist [ nick ] = { } if cmd not in self . abuselist [ nick ] : self . abuselist [ nick ] [ cmd ] = [ datetime . now ( ) ] else : self . abuselist [ nick ] [ cmd ] . append ( datetime . now ( ) ) count = 0 for x in self . abuselist [ nick ] [ cmd ] : if datetime . now ( ) - x < timedelta ( seconds = 60 ) : count = count + 1 if count > limit : msg = "%s: don't abuse scores!" if cmd == 'scores' else "%s: stop abusing the bot!" send ( msg % nick , target = target ) with self . db . session_scope ( ) as session : send ( misc . ignore ( session , nick ) ) return True | Rate - limits commands . |
15,040 | def do_log ( self , target , nick , msg , msgtype ) : if not isinstance ( msg , str ) : raise Exception ( "IRC doesn't like it when you send it a %s" % type ( msg ) . __name__ ) target = target . lower ( ) flags = 0 if target . startswith ( ( '+' , '@' ) ) : target = target [ 1 : ] with self . data_lock : if target in self . channels : if self . opers [ target ] . get ( nick , False ) : flags |= 1 if self . voiced [ target ] . get ( nick , False ) : flags |= 2 else : target = 'private' msg = msg . replace ( '\x02\x038,4' , '<rage>' ) self . db . log ( nick , target , flags , msg , msgtype ) if self . log_to_ctrlchan : ctrlchan = self . config [ 'core' ] [ 'ctrlchan' ] if target != ctrlchan : ctrlmsg = "%s:%s:%s:%s" % ( target , msgtype , nick , msg ) self . connection . privmsg ( ctrlchan , ctrlmsg . strip ( ) ) | Handles logging . |
15,041 | def do_part ( self , cmdargs , nick , target , msgtype , send , c ) : channel = self . config [ 'core' ] [ 'channel' ] botnick = self . config [ 'core' ] [ 'nick' ] if not cmdargs : if target == channel : send ( "%s must have a home." % botnick ) return else : cmdargs = target if not cmdargs . startswith ( ( '#' , '+' , '@' ) ) : cmdargs = '#' + cmdargs if cmdargs == channel : send ( "%s must have a home." % botnick ) return if cmdargs == self . config [ 'core' ] [ 'ctrlchan' ] : send ( "%s must remain under control, or bad things will happen." % botnick ) return self . send ( cmdargs , nick , "Leaving at the request of %s" % nick , msgtype ) c . part ( cmdargs ) | Leaves a channel . |
15,042 | def do_join ( self , cmdargs , nick , msgtype , send , c ) : if not cmdargs : send ( "Join what?" ) return if cmdargs == '0' : send ( "I'm sorry, Dave. I'm afraid I can't do that." ) return if not cmdargs . startswith ( ( '#' , '+' , '@' ) ) : cmdargs = '#' + cmdargs cmd = cmdargs . split ( ) if cmd [ 0 ] in self . channels and not ( len ( cmd ) > 1 and cmd [ 1 ] == "force" ) : send ( "%s is already a member of %s" % ( self . config [ 'core' ] [ 'nick' ] , cmd [ 0 ] ) ) return c . join ( cmd [ 0 ] ) self . send ( cmd [ 0 ] , nick , "Joined at the request of " + nick , msgtype ) | Join a channel . |
15,043 | def do_mode ( self , target , msg , nick , send ) : mode_changes = irc . modes . parse_channel_modes ( msg ) with self . data_lock : for change in mode_changes : if change [ 1 ] == 'v' : self . voiced [ target ] [ change [ 2 ] ] = True if change [ 0 ] == '+' else False if change [ 1 ] == 'o' : self . opers [ target ] [ change [ 2 ] ] = True if change [ 0 ] == '+' else False if [ x for x in mode_changes if self . check_mode ( x ) ] : send ( "%s: :(" % nick , target = target ) if not self . is_admin ( None , nick ) : send ( "OP %s" % target , target = 'ChanServ' ) send ( "UNBAN %s" % target , target = 'ChanServ' ) if len ( self . guarded ) > 0 : regex = r"(.*(-v|-o|\+q|\+b)[^ ]*) (%s)" % "|" . join ( self . guarded ) match = re . search ( regex , msg ) if match and nick not in [ match . group ( 3 ) , self . connection . real_nickname ] : modestring = "+voe-qb %s" % ( " " . join ( [ match . group ( 3 ) ] * 5 ) ) self . connection . mode ( target , modestring ) send ( 'Mode %s on %s by the guard system' % ( modestring , target ) , target = self . config [ 'core' ] [ 'ctrlchan' ] ) | reop and handle guard violations . |
15,044 | def do_kick ( self , send , target , nick , msg , slogan = True ) : if not self . kick_enabled : return if target not in self . channels : send ( "%s: you're lucky, private message kicking hasn't been implemented yet." % nick ) return with self . data_lock : ops = [ k for k , v in self . opers [ target ] . items ( ) if v ] botnick = self . config [ 'core' ] [ 'nick' ] if botnick not in ops : ops = [ 'someone' ] if not ops else ops send ( textutils . gen_creffett ( "%s: /op the bot" % random . choice ( ops ) ) , target = target ) elif random . random ( ) < 0.01 and msg == "shutting caps lock off" : if nick in ops : send ( "%s: HUEHUEHUE GIBE CAPSLOCK PLS I REPORT U" % nick , target = target ) else : self . connection . kick ( target , nick , "HUEHUEHUE GIBE CAPSLOCK PLS I REPORT U" ) else : msg = textutils . gen_slogan ( msg ) . upper ( ) if slogan else msg if nick in ops : send ( "%s: %s" % ( nick , msg ) , target = target ) else : self . connection . kick ( target , nick , msg ) | Kick users . |
15,045 | def do_args ( self , modargs , send , nick , target , source , name , msgtype ) : realargs = { } args = { 'nick' : nick , 'handler' : self , 'db' : None , 'config' : self . config , 'source' : source , 'name' : name , 'type' : msgtype , 'botnick' : self . connection . real_nickname , 'target' : target if target [ 0 ] == "#" else "private" , 'do_kick' : lambda target , nick , msg : self . do_kick ( send , target , nick , msg ) , 'is_admin' : lambda nick : self . is_admin ( send , nick ) , 'abuse' : lambda nick , limit , cmd : self . abusecheck ( send , nick , target , limit , cmd ) } for arg in modargs : if arg in args : realargs [ arg ] = args [ arg ] else : raise Exception ( "Invalid Argument: %s" % arg ) return realargs | Handle the various args that modules need . |
15,046 | def do_welcome ( self ) : self . rate_limited_send ( 'join' , self . config [ 'core' ] [ 'channel' ] ) self . rate_limited_send ( 'join' , self . config [ 'core' ] [ 'ctrlchan' ] , self . config [ 'auth' ] [ 'ctrlkey' ] ) self . workers . defer ( 5 , False , self . get_admins ) extrachans = self . config [ 'core' ] [ 'extrachans' ] if extrachans : for chan in [ x . strip ( ) for x in extrachans . split ( ',' ) ] : self . rate_limited_send ( 'join' , chan ) | Do setup when connected to server . |
15,047 | def get_filtered_send ( self , cmdargs , send , target ) : parser = arguments . ArgParser ( self . config ) parser . add_argument ( '--filter' ) try : filterargs , remainder = parser . parse_known_args ( cmdargs ) except arguments . ArgumentException as ex : return str ( ex ) , None cmdargs = ' ' . join ( remainder ) if filterargs . filter is None : return cmdargs , send filter_list , output = textutils . append_filters ( filterargs . filter ) if filter_list is None : return output , None def filtersend ( msg , mtype = 'privmsg' , target = target , ignore_length = False ) : self . send ( target , self . connection . real_nickname , msg , mtype , ignore_length , filters = filter_list ) return cmdargs , filtersend | Parse out any filters . |
15,048 | def handle_msg ( self , c , e ) : if e . type not in [ 'authenticate' , 'error' , 'join' , 'part' , 'quit' ] : nick = e . source . nick else : nick = e . source if e . arguments is None : msg = "" else : msg = " " . join ( e . arguments ) . strip ( ) target = nick if e . type == 'privmsg' else e . target def send ( msg , mtype = 'privmsg' , target = target , ignore_length = False ) : self . send ( target , self . connection . real_nickname , msg , mtype , ignore_length ) if e . type in [ 'account' , 'authenticate' , 'bannedfromchan' , 'cap' , 'ctcpreply' , 'error' , 'featurelist' , 'nosuchnick' , 'nick' , 'nicknameinuse' , 'privnotice' , 'welcome' , 'whospcrpl' ] : self . handle_event ( msg , send , c , e ) return if not msg and e . type != 'join' : return self . do_log ( target , nick , msg , e . type ) if e . type == 'mode' : self . do_mode ( target , msg , nick , send ) return if e . type == 'join' : self . handle_join ( c , e , target , send ) return if e . type == 'part' : if nick == c . real_nickname : send ( "Parted channel %s" % target , target = self . config [ 'core' ] [ 'ctrlchan' ] ) return if e . type == 'kick' : self . handle_kick ( c , e , target , send ) return if e . target == self . config [ 'core' ] [ 'ctrlchan' ] and self . is_admin ( None , nick ) : control . handle_ctrlchan ( self , msg , nick , send ) if self . is_ignored ( nick ) and not self . is_admin ( None , nick ) : return self . handle_hooks ( send , nick , target , e , msg ) if e . type == 'pubnotice' : return msg = misc . get_cmdchar ( self . config , c , msg , e . type ) cmd_name , cmdargs = self . get_cmd ( msg ) if registry . command_registry . is_registered ( cmd_name ) : self . run_cmd ( send , nick , target , cmd_name , cmdargs , e ) elif cmd_name == 'reload' : with self . db . session_scope ( ) as session : if session . query ( orm . Permissions ) . filter ( orm . Permissions . nick == nick ) . count ( ) : send ( "Aye Aye Capt'n" ) | The Heart and Soul of IrcBot . |
15,049 | def process_tag ( self , tag ) : try : if not self . _is_function ( tag ) : self . _tag_type_processor [ tag . data_type ] ( tag ) except KeyError as ex : raise Exception ( 'Tag type {0} not recognized for tag {1}' . format ( tag . data_type , tag . name ) , ex ) | Processes tag and detects which function to use |
15,050 | def process_boolean ( self , tag ) : tag . set_address ( self . normal_register . current_bit_address ) self . normal_register . move_to_next_bit_address ( ) | Process Boolean type tags |
15,051 | def process_boolean_array ( self , tag ) : array_size = tag . get_array_size ( ) tag . set_address ( self . normal_register . get_array ( array_size ) ) if self . is_sixteen_bit : self . normal_register . move_to_next_address ( ( array_size / 16 ) + 1 ) return self . normal_register . move_to_next_address ( ( array_size / 8 ) + 1 ) | Process Boolean array type tags |
15,052 | def process_byte ( self , tag ) : tag . set_address ( self . normal_register . current_address ) self . normal_register . move_to_next_address ( 1 ) | Process byte type tags |
15,053 | def process_string ( self , tag ) : tag . set_address ( self . string_register . current_address ) if self . is_sixteen_bit : self . string_register . move_to_next_address ( 1 ) return self . string_register . move_to_next_address ( 1 ) | Process string type tags |
15,054 | def cmd ( send , msg , args ) : nick = args [ 'nick' ] channel = args [ 'target' ] if args [ 'target' ] != 'private' else args [ 'config' ] [ 'core' ] [ 'channel' ] levels = { 1 : 'Whirr...' , 2 : 'Vrrm...' , 3 : 'Zzzzhhhh...' , 4 : 'SHFRRRRM...' , 5 : 'GEEEEZZSH...' , 6 : 'PLAAAAIIID...' , 7 : 'KKKRRRAAKKKAAKRAKKGGARGHGIZZZZ...' , 8 : 'Nuke' , 9 : 'nneeeaaaooowwwwww..... BOOOOOSH BLAM KABOOM' , 10 : 'ssh root@remote.tjhsst.edu rm -rf ~%s' } if not msg : send ( 'What to microwave?' ) return match = re . match ( '(-?[0-9]*) (.*)' , msg ) if not match : send ( 'Power level?' ) else : level = int ( match . group ( 1 ) ) target = match . group ( 2 ) if level > 10 : send ( 'Aborting to prevent extinction of human race.' ) return if level < 1 : send ( 'Anti-matter not yet implemented.' ) return if level > 7 : if not args [ 'is_admin' ] ( nick ) : send ( "I'm sorry. Nukes are a admin-only feature" ) return elif msg == args [ 'botnick' ] : send ( "Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge." ) else : with args [ 'handler' ] . data_lock : if target not in args [ 'handler' ] . channels [ channel ] . users ( ) : send ( "I'm sorry. Anonymous Nuking is not allowed" ) return msg = levels [ 1 ] for i in range ( 2 , level + 1 ) : if i < 8 : msg += ' ' + levels [ i ] send ( msg ) if level >= 8 : do_nuke ( args [ 'handler' ] . connection , nick , target , channel ) if level >= 9 : send ( levels [ 9 ] ) if level == 10 : send ( levels [ 10 ] % target ) send ( 'Ding, your %s is ready.' % target ) | Microwaves something . |
15,055 | async def main ( ) : async with aiohttp . ClientSession ( ) as session : station = OpenSenseMap ( SENSOR_ID , loop , session ) await station . get_data ( ) print ( "Name:" , station . name ) print ( "Description:" , station . description ) print ( "Coordinates:" , station . coordinates ) print ( "PM 2.5:" , station . pm2_5 ) print ( "PM 10:" , station . pm10 ) print ( "Temperature:" , station . temperature ) | Sample code to retrieve the data from an OpenSenseMap station . |
15,056 | def theme ( self , text ) : return self . theme_color + self . BRIGHT + text + self . RESET | Theme style . |
15,057 | def _label_desc ( self , label , desc , label_color = '' ) : return self . BRIGHT + label_color + label + self . RESET + desc | Generic styler for a line consisting of a label and description . |
15,058 | def error ( self , cmd , desc = '' ) : return self . _label_desc ( cmd , desc , self . error_color ) | Style for an error message . |
15,059 | def warn ( self , cmd , desc = '' ) : return self . _label_desc ( cmd , desc , self . warn_color ) | Style for warning message . |
15,060 | def success ( self , cmd , desc = '' ) : return self . _label_desc ( cmd , desc , self . success_color ) | Style for a success message . |
15,061 | def cmdloop ( self , intro = None ) : self . preloop ( ) if self . use_rawinput and self . completekey : try : import readline self . old_completer = readline . get_completer ( ) readline . set_completer ( self . complete ) readline . parse_and_bind ( self . completekey + ': complete' ) except ImportError : pass try : if intro is not None : self . intro = intro if self . intro : self . stdout . write ( str ( self . intro ) + "\n" ) stop = None while not stop : if self . cmdqueue : line = self . cmdqueue . pop ( 0 ) else : if self . use_rawinput : try : if sys . version_info [ 0 ] == 2 : line = raw_input ( self . prompt ) else : line = input ( self . prompt ) except EOFError : line = 'EOF' except KeyboardInterrupt : line = 'ctrlc' else : self . stdout . write ( self . prompt ) self . stdout . flush ( ) line = self . stdin . readline ( ) if not len ( line ) : line = 'EOF' else : line = line . rstrip ( '\r\n' ) line = self . precmd ( line ) stop = self . onecmd ( line ) stop = self . postcmd ( stop , line ) self . postloop ( ) finally : if self . use_rawinput and self . completekey : try : import readline readline . set_completer ( self . old_completer ) except ImportError : pass | Override the command loop to handle Ctrl - C . |
15,062 | def do_exit ( self , arg ) : if self . arm . is_connected ( ) : self . arm . disconnect ( ) print ( 'Bye!' ) return True | Exit the shell . |
15,063 | def do_ctrlc ( self , arg ) : print ( 'STOP' ) if self . arm . is_connected ( ) : self . arm . write ( 'STOP' ) | Ctrl - C sends a STOP command to the arm . |
15,064 | def do_status ( self , arg ) : info = self . arm . get_info ( ) max_len = len ( max ( info . keys ( ) , key = len ) ) print ( self . style . theme ( '\nArm Status' ) ) for key , value in info . items ( ) : print ( self . style . help ( key . ljust ( max_len + 2 ) , str ( value ) ) ) print ( ) | Print information about the arm . |
15,065 | def do_connect ( self , arg ) : if self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is already connected.' ) ) else : try : port = self . arm . connect ( ) print ( self . style . success ( 'Success: ' , 'Connected to \'{}\'.' . format ( port ) ) ) except r12 . ArmException as e : print ( self . style . error ( 'Error: ' , str ( e ) ) ) | Connect to the arm . |
15,066 | def do_disconnect ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is already disconnected.' ) ) else : self . arm . disconnect ( ) print ( self . style . success ( 'Success: ' , 'Disconnected.' ) ) | Disconnect from the arm . |
15,067 | def do_run ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is not connected.' ) ) return try : with open ( arg ) as f : lines = [ line . strip ( ) for line in f . readlines ( ) ] except IOError : print ( self . style . error ( 'Error: ' , 'Could not load file \'{}\'.' . format ( arg ) ) ) return for line in lines : if self . wrapper : line = self . wrapper . wrap_input ( line ) self . arm . write ( line ) res = self . arm . read ( ) if self . wrapper : res = self . wrapper . wrap_output ( res ) print ( res ) | Load and run an external FORTH script . |
15,068 | def do_dump ( self , arg ) : if not self . arm . is_connected ( ) : print ( self . style . error ( 'Error: ' , 'Arm is not connected.' ) ) return print ( self . arm . dump ( ) ) | Output all bytes waiting in output queue . |
15,069 | def complete_run ( self , text , line , b , e ) : text = line . split ( ) [ - 1 ] forth_files = glob . glob ( text + '*.fs' ) if len ( forth_files ) == 0 : return [ f . split ( os . path . sep ) [ - 1 ] for f in glob . glob ( text + '*' ) ] forth_files = [ f . split ( os . path . sep ) [ - 1 ] for f in forth_files ] return forth_files | Autocomplete file names with . forth ending . |
15,070 | def get_names ( self ) : return ( [ 'do_' + x for x in self . commands [ 'shell' ] ] + [ 'do_' + x for x in self . commands [ 'forth' ] ] ) | Get names for autocompletion . |
15,071 | def parse_help_text ( self , file_path ) : with open ( file_path ) as f : lines = f . readlines ( ) cmds = [ ] descs = [ ] for line in lines : line = line . strip ( ) if len ( line ) == 0 : cmds . append ( '' ) descs . append ( '' ) else : tokens = line . split ( ' ' ) cmds . append ( tokens [ 0 ] ) descs . append ( '' . join ( tokens [ 1 : ] ) . strip ( ) ) max_len = len ( max ( cmds , key = len ) ) text = '' for cmd , desc in zip ( cmds , descs ) : if len ( cmd ) == 0 : text += '\n' else : text += self . style . help ( cmd . ljust ( max_len + 2 ) , desc + '\n' ) return cmds , text | Load of list of commands and descriptions from a file . |
15,072 | def load_forth_commands ( self , help_dir ) : try : help_file_path = os . path . join ( help_dir , 'roboforth.txt' ) commands , help_text = self . parse_help_text ( help_file_path ) except IOError : print ( self . style . warn ( 'Warning: ' , 'Failed to load ROBOFORTH help.' ) ) return self . commands [ 'forth' ] = commands self . help [ 'forth' ] = '\n' . join ( [ self . style . theme ( 'Forth Commands' ) , help_text ] ) | Load completion list for ROBOFORTH commands . |
15,073 | def preloop ( self ) : script_dir = os . path . dirname ( os . path . realpath ( __file__ ) ) help_dir = os . path . join ( script_dir , HELP_DIR_NAME ) self . load_forth_commands ( help_dir ) self . load_shell_commands ( help_dir ) | Executed before the command loop starts . |
15,074 | def bootstrap_legislative_office ( self , election ) : body = election . race . office . body body_division = election . race . office . body . jurisdiction . division office_division = election . race . office . division self . bootstrap_federal_body_type_page ( election ) self . bootstrap_state_body_type_page ( election ) PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( body ) , object_id = body . pk , election_day = election . election_day , division = body_division , ) if office_division . level . name == DivisionLevel . STATE : PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( office_division ) , object_id = office_division . pk , election_day = election . election_day , special_election = False , ) elif office_division . level . name == DivisionLevel . DISTRICT : PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( office_division . parent ) , object_id = office_division . parent . pk , election_day = election . election_day , special_election = False , ) page_type , created = PageType . objects . get_or_create ( model_type = ContentType . objects . get ( app_label = "geography" , model = "division" ) , election_day = election . election_day , division_level = DivisionLevel . objects . get ( name = DivisionLevel . STATE ) , ) PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( page_type ) , object_id = page_type . pk , election_day = election . election_day , ) | For legislative offices create page content for the legislative Body the Office belongs to AND the state - level Division . |
15,075 | def cmd ( send , msg , args ) : latest = get_latest ( ) if not msg : msg = randrange ( 1 , latest ) elif msg == 'latest' : msg = latest elif msg . isdigit ( ) : msg = int ( msg ) if msg > latest or msg < 1 : send ( "Number out of range" ) return else : send ( do_search ( msg , args [ 'config' ] [ 'api' ] [ 'googleapikey' ] , args [ 'config' ] [ 'api' ] [ 'xkcdsearchid' ] ) ) return url = 'http://xkcd.com/%d/info.0.json' % msg if msg != 'latest' else 'http://xkcd.com/info.0.json' data = get ( url ) . json ( ) output = "%s -- http://xkcd.com/%d" % ( data [ 'safe_title' ] , data [ 'num' ] ) send ( output ) | Gets a xkcd comic . |
15,076 | def generate_config_parser ( config , include_all = False ) : config_parser = SafeConfigParser ( allow_no_value = True ) for section_name , option_name in _get_included_schema_sections_options ( config , include_all ) : if not config_parser . has_section ( section_name ) : config_parser . add_section ( section_name ) option = config [ section_name ] [ option_name ] if option . get ( 'required' ) : config_parser . set ( section_name , '# REQUIRED' ) config_parser . set ( section_name , '# ' + option . get ( 'description' , 'No description provided.' ) ) if option . get ( 'deprecated' ) : config_parser . set ( section_name , '# DEPRECATED' ) option_value = _get_value ( option ) config_parser . set ( section_name , option_name , option_value ) config_parser . set ( section_name , '' ) return config_parser | Generates a config parser from a configuration dictionary . |
15,077 | def generate_documentation ( schema ) : documentation_title = "Configuration documentation" documentation = documentation_title + "\n" documentation += "=" * len ( documentation_title ) + '\n' for section_name in schema : section_created = False for option_name in schema [ section_name ] : option = schema [ section_name ] [ option_name ] if not section_created : documentation += '\n' documentation += section_name + '\n' documentation += '-' * len ( section_name ) + '\n' section_created = True documentation += '\n' documentation += option_name + '\n' documentation += '~' * len ( option_name ) + '\n' if option . get ( 'required' ) : documentation += "** This option is required! **\n" if option . get ( 'type' ) : documentation += '*Type : %s.*\n' % option . get ( 'type' ) if option . get ( 'description' ) : documentation += option . get ( 'description' ) + '\n' if option . get ( 'default' ) : documentation += 'The default value is %s.\n' % option . get ( 'default' ) if option . get ( 'deprecated' ) : documentation += "** This option is deprecated! **\n" return documentation | Generates reStructuredText documentation from a Confirm file . |
15,078 | def append_existing_values ( schema , config ) : for section_name in config : for option_name in config [ section_name ] : option_value = config [ section_name ] [ option_name ] schema . setdefault ( section_name , { } ) . setdefault ( option_name , { } ) [ 'value' ] = option_value return schema | Adds the values of the existing config to the config dictionary . |
15,079 | def generate_schema_file ( config_file ) : config = utils . load_config_from_ini_file ( config_file ) schema = { } for section_name in config : for option_name in config [ section_name ] : schema . setdefault ( section_name , { } ) . setdefault ( option_name , { } ) schema [ section_name ] [ option_name ] [ 'description' ] = 'No description provided.' return utils . dump_schema_file ( schema ) | Generates a basic confirm schema file from a configuration file . |
15,080 | def rankwithlist ( l , lwith , test = False ) : if not ( isinstance ( l , list ) and isinstance ( lwith , list ) ) : l , lwith = list ( l ) , list ( lwith ) from scipy . stats import rankdata if test : print ( l , lwith ) print ( rankdata ( l ) , rankdata ( lwith ) ) print ( rankdata ( l + lwith ) ) return rankdata ( l + lwith ) [ : len ( l ) ] | rank l wrt lwith |
15,081 | def dfbool2intervals ( df , colbool ) : df . index = range ( len ( df ) ) intervals = bools2intervals ( df [ colbool ] ) for intervali , interval in enumerate ( intervals ) : df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval id' ] = intervali df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval start' ] = interval [ 0 ] df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval stop' ] = interval [ 1 ] df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval length' ] = interval [ 1 ] - interval [ 0 ] + 1 df . loc [ interval [ 0 ] : interval [ 1 ] , f'{colbool} interval within index' ] = range ( interval [ 1 ] - interval [ 0 ] + 1 ) df [ f'{colbool} interval index' ] = df . index return df | ds contains bool values |
15,082 | def normalize_kind ( self , kindlike ) : if kindlike is None : return ( object , ) elif isinstance ( kindlike , type ) : return ( kindlike , ) else : return tuple ( kindlike ) | Make a kind out of a possible shorthand . If the given argument is a sequence of types or a singular type it becomes a kind that accepts exactly those types . If the given argument is None it becomes a type that accepts anything . |
15,083 | def str_kind ( self , kind ) : if len ( kind ) == 0 : return 'Nothing' elif len ( kind ) == 1 : return kind [ 0 ] . __name__ elif len ( kind ) == 2 : return kind [ 0 ] . __name__ + ' or ' + kind [ 1 ] . __name__ else : return 'one of {' + ', ' . join ( t . __name__ for t in kind ) + '}' | Get a string describing a kind . |
15,084 | def checktype ( self , val , kind , ** kargs ) : if not isinstance ( val , kind ) : raise TypeError ( 'Expected {}; got {}' . format ( self . str_kind ( kind ) , self . str_valtype ( val ) ) ) | Raise TypeError if val does not satisfy kind . |
15,085 | def raises ( cls , sender , attrname , error , args = ANYTHING , kwargs = ANYTHING ) : "An alternative constructor which raises the given error" def raise_error ( ) : raise error return cls ( sender , attrname , returns = Invoke ( raise_error ) , args = ANYTHING , kwargs = ANYTHING ) | An alternative constructor which raises the given error |
15,086 | def and_raises ( self , * errors ) : "Expects an error or more to be raised from the given expectation." for error in errors : self . __expect ( Expectation . raises , error ) | Expects an error or more to be raised from the given expectation . |
15,087 | def and_calls ( self , * funcs ) : for fn in funcs : self . __expect ( Expectation , Invoke ( fn ) ) | Expects the return value from one or more functions to be raised from the given expectation . |
15,088 | def and_yields ( self , * values ) : def generator ( ) : for value in values : yield value self . __expect ( Expectation , Invoke ( generator ) ) | Expects the return value of the expectation to be a generator of the given values |
15,089 | def attribute_invoked ( self , sender , name , args , kwargs ) : "Handles the creation of ExpectationBuilder when an attribute is invoked." return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , '__call__' ) ( * args , ** kwargs ) | Handles the creation of ExpectationBuilder when an attribute is invoked . |
15,090 | def attribute_read ( self , sender , name ) : "Handles the creation of ExpectationBuilder when an attribute is read." return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , name ) | Handles the creation of ExpectationBuilder when an attribute is read . |
15,091 | def key_read ( self , sender , name ) : "Handles the creation of ExpectationBuilder when a dictionary item access." return ExpectationBuilder ( self . sender , self . delegate , self . add_invocation , self . add_expectations , '__getitem__' ) ( name ) | Handles the creation of ExpectationBuilder when a dictionary item access . |
15,092 | def friendly_load ( parser , token ) : bits = token . contents . split ( ) if len ( bits ) >= 4 and bits [ - 2 ] == "from" : name = bits [ - 1 ] try : lib = find_library ( parser , name ) subset = load_from_library ( lib , name , bits [ 1 : - 2 ] ) parser . add_library ( subset ) except TemplateSyntaxError : pass else : for name in bits [ 1 : ] : try : lib = find_library ( parser , name ) parser . add_library ( lib ) except TemplateSyntaxError : pass return LoadNode ( ) | Tries to load a custom template tag set . Non existing tag libraries are ignored . |
15,093 | def off ( self ) : self . win . keypad ( 0 ) curses . nocbreak ( ) curses . echo ( ) try : curses . curs_set ( 1 ) except : pass curses . endwin ( ) | Turn off curses |
15,094 | def _move_agent ( self , agent , direction , wrap_allowed = True ) : x , y = agent . coords [ 'x' ] , agent . coords [ 'y' ] print ( 'moving agent ' , agent . name , 'to x,y=' , direction , 'wrap_allowed = ' , wrap_allowed ) agent . coords [ 'x' ] = x + direction [ 0 ] agent . coords [ 'y' ] = y + direction [ 1 ] | moves agent agent in direction |
15,095 | def key_func ( * keys , ** kwargs ) : ensure_argcount ( keys , min_ = 1 ) ensure_keyword_args ( kwargs , optional = ( 'default' , ) ) keys = list ( map ( ensure_string , keys ) ) if 'default' in kwargs : default = kwargs [ 'default' ] def getitems ( obj ) : for key in keys : try : obj = obj [ key ] except KeyError : return default return obj else : if len ( keys ) == 1 : getitems = operator . itemgetter ( keys [ 0 ] ) else : def getitems ( obj ) : for key in keys : obj = obj [ key ] return obj return getitems | Creates a key function based on given keys . |
15,096 | def find_files ( path , patterns ) : if not isinstance ( patterns , ( list , tuple ) ) : patterns = [ patterns ] matches = [ ] for root , dirnames , filenames in os . walk ( path ) : for pattern in patterns : for filename in fnmatch . filter ( filenames , pattern ) : matches . append ( os . path . join ( root , filename ) ) return matches | Returns all files from a given path that matches the pattern or list of patterns |
15,097 | def recursive_update ( _dict , _update ) : for k , v in _update . items ( ) : if isinstance ( v , collections . Mapping ) : r = recursive_update ( _dict . get ( k , { } ) , v ) _dict [ k ] = r else : _dict [ k ] = _update [ k ] return _dict | Same as dict . update but updates also nested dicts instead of overriding then |
15,098 | def validate ( self , value ) : if not self . blank and value == '' : self . error_message = 'Can not be empty. Please provide a value.' return False self . _choice = value return True | The most basic validation |
15,099 | def validate ( self , value ) : if '.' not in value : self . error_message = '%s is not a fully qualified domain name.' % value return False try : ipaddress = socket . gethostbyname ( value ) except socket . gaierror : self . error_message = '%s does not resolve.' % value return False try : socket . gethostbyaddr ( ipaddress ) except socket . herror : self . error_message = '%s reverse address (%s) does not resolve.' % ( value , ipaddress ) return False self . _choice = value return True | Attempts a forward lookup via the socket library and if successful will try to do a reverse lookup to verify DNS is returning both lookups . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.