idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
15,100 | def __list_updates ( update_type , update_list ) : if len ( update_list ) : print ( " %s:" % update_type ) for update_item in update_list : print ( " -- %(version)s on %(upload_time)s" % update_item ) | Function used to list package updates by update type in console | 67 | 11 |
15,101 | def __updatable ( ) : # Add argument for console parser = argparse . ArgumentParser ( ) parser . add_argument ( 'file' , nargs = '?' , type = argparse . FileType ( ) , default = None , help = 'Requirements file' ) args = parser . parse_args ( ) # Get list of packages if args . file : packages = parse_requirements_list ( args . file ) else : packages = get_parsed_environment_package_list ( ) # Output updates for package in packages : __list_package_updates ( package [ 'package' ] , package [ 'version' ] ) | Function used to output packages update information in the console | 138 | 10 |
15,102 | def handle ( send , msg , args ) : worker = args [ "handler" ] . workers result = worker . run_pool ( get_urls , [ msg ] ) try : urls = result . get ( 5 ) except multiprocessing . TimeoutError : worker . restart_pool ( ) send ( "Url regex timed out." , target = args [ "config" ] [ "core" ] [ "ctrlchan" ] ) return for url in urls : # Prevent botloops if ( args [ "db" ] . query ( Urls ) . filter ( Urls . url == url , Urls . time > datetime . now ( ) - timedelta ( seconds = 10 ) ) . count ( ) > 1 ) : return if url . startswith ( "https://twitter.com" ) : tid = url . split ( "/" ) [ - 1 ] twitter_api = get_api ( args [ "config" ] ) status = twitter_api . GetStatus ( tid ) text = status . text . replace ( "\n" , " / " ) send ( "** {} (@{}) on Twitter: {}" . format ( status . user . name , status . user . screen_name , text ) ) return imgkey = args [ "config" ] [ "api" ] [ "googleapikey" ] title = urlutils . get_title ( url , imgkey ) shortkey = args [ "config" ] [ "api" ] [ "bitlykey" ] short = urlutils . get_short ( url , shortkey ) last = args [ "db" ] . query ( Urls ) . filter ( Urls . url == url ) . order_by ( Urls . time . desc ( ) ) . first ( ) if args [ "config" ] [ "feature" ] . getboolean ( "linkread" ) : if last is not None : lasttime = last . time . strftime ( "%H:%M:%S on %Y-%m-%d" ) send ( "Url %s previously posted at %s by %s -- %s" % ( short , lasttime , last . nick , title ) ) else : send ( "** %s - %s" % ( title , short ) ) args [ "db" ] . add ( Urls ( url = url , title = title , nick = args [ "nick" ] , time = datetime . now ( ) ) ) | Get titles for urls . | 525 | 6 |
15,103 | def page_location_template ( self ) : cycle = self . election_day . cycle . name model_class = self . model_type . model_class ( ) if model_class == ElectionDay : return "/{}/" . format ( cycle ) if model_class == Office : # President if self . jurisdiction : if self . division_level . name == DivisionLevel . STATE : return "/{}/president/{{state}}" . format ( cycle ) else : return "/{}/president/" . format ( cycle ) # Governor else : return "/{}/{{state}}/governor/" . format ( cycle ) elif model_class == Body : # Senate if self . body . slug == "senate" : if self . jurisdiction : if self . division_level . name == DivisionLevel . STATE : return "/{}/senate/{{state}}/" . format ( cycle ) else : return "/{}/senate/" . format ( cycle ) else : return "/{}/{{state}}/senate/" . format ( cycle ) # House else : if self . jurisdiction : if self . division_level . name == DivisionLevel . STATE : return "/{}/house/{{state}}/" . format ( cycle ) else : return "/{}/house/" . format ( cycle ) else : return "/{}/{{state}}/house/" . format ( cycle ) elif model_class == Division : return "/{}/{{state}}/" . format ( cycle ) else : return "ORPHAN TYPE" | Returns the published URL template for a page type . | 327 | 10 |
15,104 | def cmd ( send , msg , _ ) : if not msg : url = 'http://tjbash.org/random1.html' params = { } else : targs = msg . split ( ) if len ( targs ) == 1 and targs [ 0 ] . isnumeric ( ) : url = 'http://tjbash.org/%s' % targs [ 0 ] params = { } else : url = 'http://tjbash.org/search.html' params = { 'query' : 'tag:%s' % '+' . join ( targs ) } req = get ( url , params = params ) doc = fromstring ( req . text ) quotes = doc . find_class ( 'quote-body' ) if not quotes : send ( "There were no results." ) return quote = choice ( quotes ) lines = [ x . strip ( ) for x in map ( operator . methodcaller ( 'strip' ) , quote . itertext ( ) ) ] # Only send up to three lines. for line in lines [ : 4 ] : send ( line ) tags = quote . getparent ( ) . find_class ( 'quote-tags' ) postid = quote . getparent ( ) . getparent ( ) . get ( 'id' ) . replace ( 'quote-' , '' ) if tags : tags = [ x . text for x in tags [ 0 ] . findall ( './/a' ) ] send ( " -- {} -- {}http://tjbash.org/{}" . format ( ', ' . join ( tags ) , "continued: " if ( len ( lines ) > 3 ) else "" , postid ) ) else : send ( " -- http://tjbash.org/{}" . format ( postid ) ) | Finds a random quote from tjbash . org given search criteria . | 382 | 15 |
15,105 | def get_queryset ( self ) : try : date = ElectionDay . objects . get ( date = self . kwargs [ 'date' ] ) except Exception : raise APIException ( 'No elections on {}.' . format ( self . kwargs [ 'date' ] ) ) body_ids = [ ] for election in date . elections . all ( ) : body = election . race . office . body if body : body_ids . append ( body . uid ) return Body . objects . filter ( uid__in = body_ids ) | Returns a queryset of all bodies holding an election on a date . | 118 | 15 |
15,106 | def configure_engine ( cls , url : Union [ str , URL , Dict [ str , Any ] ] = None , bind : Union [ Connection , Engine ] = None , session : Dict [ str , Any ] = None , ready_callback : Union [ Callable [ [ Engine , sessionmaker ] , Any ] , str ] = None , poolclass : Union [ str , Pool ] = None , * * engine_args ) : assert check_argument_types ( ) if bind is None : if isinstance ( url , dict ) : url = URL ( * * url ) elif isinstance ( url , str ) : url = make_url ( url ) elif url is None : raise TypeError ( 'both "url" and "bind" cannot be None' ) if isinstance ( poolclass , str ) : poolclass = resolve_reference ( poolclass ) # This is a hack to get SQLite to play nice with asphalt-sqlalchemy's juggling of # connections between multiple threads. The same connection should, however, never be # used in multiple threads at once. if url . get_dialect ( ) . name == 'sqlite' : connect_args = engine_args . setdefault ( 'connect_args' , { } ) connect_args . setdefault ( 'check_same_thread' , False ) bind = create_engine ( url , poolclass = poolclass , * * engine_args ) session = session or { } session . setdefault ( 'expire_on_commit' , False ) ready_callback = resolve_reference ( ready_callback ) return bind , sessionmaker ( bind , * * session ) , ready_callback | Create an engine and selectively apply certain hacks to make it Asphalt friendly . | 353 | 15 |
15,107 | def valid_file ( value ) : if not value : raise argparse . ArgumentTypeError ( "'' is not a valid file path" ) elif not os . path . exists ( value ) : raise argparse . ArgumentTypeError ( "%s is not a valid file path" % value ) elif os . path . isdir ( value ) : raise argparse . ArgumentTypeError ( "%s is a directory, not a regular file" % value ) return value | Check if given file exists and is a regular file . | 98 | 11 |
15,108 | def valid_level ( value ) : value = value . upper ( ) if getattr ( logging , value , None ) is None : raise argparse . ArgumentTypeError ( "%s is not a valid level" % value ) return value | Validation function for parser logging level argument . | 49 | 9 |
15,109 | def get_logger ( cls , custom_name = None ) : name = custom_name or cls . get_name ( ) return logging . getLogger ( name ) | Returns a logger for the plugin . | 39 | 7 |
15,110 | def all ( self , domain = None ) : if domain is None : return { k : dict ( v ) for k , v in list ( self . messages . items ( ) ) } return dict ( self . messages . get ( domain , { } ) ) | Gets the messages within a given domain . | 54 | 9 |
15,111 | def set ( self , id , translation , domain = 'messages' ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( translation , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) self . add ( { id : translation } , domain ) | Sets a message translation . | 68 | 6 |
15,112 | def has ( self , id , domain ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) if self . defines ( id , domain ) : return True if self . fallback_catalogue is not None : return self . fallback_catalogue . has ( id , domain ) return False | Checks if a message has a translation . | 77 | 9 |
15,113 | def get ( self , id , domain = 'messages' ) : assert isinstance ( id , ( str , unicode ) ) assert isinstance ( domain , ( str , unicode ) ) if self . defines ( id , domain ) : return self . messages [ domain ] [ id ] if self . fallback_catalogue is not None : return self . fallback_catalogue . get ( id , domain ) return id | Gets a message translation . | 90 | 6 |
15,114 | def replace ( self , messages , domain = 'messages' ) : assert isinstance ( messages , ( dict , CaseInsensitiveDict ) ) assert isinstance ( domain , ( str , unicode ) ) self . messages [ domain ] = CaseInsensitiveDict ( { } ) self . add ( messages , domain ) | Sets translations for a given domain . | 68 | 8 |
15,115 | def add_catalogue ( self , catalogue ) : assert isinstance ( catalogue , MessageCatalogue ) if catalogue . locale != self . locale : raise ValueError ( 'Cannot add a catalogue for locale "%s" as the ' 'current locale for this catalogue is "%s"' % ( catalogue . locale , self . locale ) ) for domain , messages in list ( catalogue . all ( ) . items ( ) ) : self . add ( messages , domain ) for resource in catalogue . resources : self . add_resource ( resource ) | Merges translations from the given Catalogue into the current one . The two catalogues must have the same locale . | 110 | 23 |
15,116 | def add_fallback_catalogue ( self , catalogue ) : assert isinstance ( catalogue , MessageCatalogue ) # detect circular references c = self while True : if c . locale == catalogue . locale : raise ValueError ( 'Circular reference detected when adding a ' 'fallback catalogue for locale "%s".' % catalogue . locale ) c = c . parent if c is None : break catalogue . parent = self self . fallback_catalogue = catalogue for resource in catalogue . resources : self . add_resource ( resource ) | Merges translations from the given Catalogue into the current one only when the translation does not exist . | 111 | 20 |
15,117 | def trans ( self , id , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } assert isinstance ( parameters , dict ) if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' msg = self . get_catalogue ( locale ) . get ( id , domain ) return self . format ( msg , parameters ) | Translates the given message . | 99 | 7 |
15,118 | def set_fallback_locales ( self , locales ) : # needed as the fallback locales are linked to the already loaded # catalogues self . catalogues = { } for locale in locales : self . _assert_valid_locale ( locale ) self . fallback_locales = locales | Sets the fallback locales . | 67 | 8 |
15,119 | def get_messages ( self , locale = None ) : if locale is None : locale = self . locale if locale not in self . catalogues : self . _load_catalogue ( locale ) catalogues = [ self . catalogues [ locale ] ] catalogue = catalogues [ 0 ] while True : catalogue = catalogue . fallback_catalogue if catalogue is None : break catalogues . append ( catalogue ) messages = { } for catalogue in catalogues [ : : - 1 ] : recursive_update ( messages , catalogue . all ( ) ) return messages | Collects all messages for the given locale . | 116 | 9 |
15,120 | def trans ( self , id , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' catalogue = self . get_catalogue ( locale ) if not catalogue . has ( id , domain ) : raise RuntimeError ( "There is no translation for {0} in domain {1}" . format ( id , domain ) ) msg = self . get_catalogue ( locale ) . get ( id , domain ) return self . format ( msg , parameters ) | Throws RuntimeError whenever a message is missing | 139 | 9 |
15,121 | def transchoice ( self , id , number , parameters = None , domain = None , locale = None ) : if parameters is None : parameters = { } if locale is None : locale = self . locale else : self . _assert_valid_locale ( locale ) if domain is None : domain = 'messages' catalogue = self . get_catalogue ( locale ) while not catalogue . defines ( id , domain ) : cat = catalogue . fallback_catalogue if cat : catalogue = cat locale = catalogue . locale else : break if not catalogue . has ( id , domain ) : raise RuntimeError ( "There is no translation for {0} in domain {1}" . format ( id , domain ) ) parameters [ 'count' ] = number msg = selector . select_message ( catalogue . get ( id , domain ) , number , locale ) return self . format ( msg , parameters ) | Raises a RuntimeError whenever a message is missing | 187 | 10 |
15,122 | def get_catalogue ( self , locale ) : if locale is None : locale = self . locale if locale not in self . catalogues or datetime . now ( ) - self . last_reload > timedelta ( seconds = 1 ) : self . _load_catalogue ( locale ) self . last_reload = datetime . now ( ) return self . catalogues [ locale ] | Reloads messages catalogue if requested after more than one second since last reload | 83 | 15 |
15,123 | def do_reload ( bot , target , cmdargs , server_send = None ) : def send ( msg ) : if server_send is not None : server_send ( "%s\n" % msg ) else : do_log ( bot . connection , bot . get_target ( target ) , msg ) confdir = bot . handler . confdir if cmdargs == 'pull' : # Permission checks. if isinstance ( target , irc . client . Event ) and target . source . nick != bot . config [ 'auth' ] [ 'owner' ] : bot . connection . privmsg ( bot . get_target ( target ) , "Nope, not gonna do it." ) return if exists ( join ( confdir , '.git' ) ) : send ( misc . do_pull ( srcdir = confdir ) ) else : send ( misc . do_pull ( repo = bot . config [ 'api' ] [ 'githubrepo' ] ) ) # Reload config importlib . reload ( config ) bot . config = config . load_config ( join ( confdir , 'config.cfg' ) , send ) # Reimport helpers errored_helpers = modutils . scan_and_reimport ( 'helpers' ) if errored_helpers : send ( "Failed to load some helpers." ) for error in errored_helpers : send ( "%s: %s" % error ) return False if not load_modules ( bot . config , confdir , send ) : return False # preserve data data = bot . handler . get_data ( ) bot . shutdown_mp ( ) bot . handler = handler . BotHandler ( bot . config , bot . connection , bot . channels , confdir ) bot . handler . set_data ( data ) bot . handler . connection = bot . connection bot . handler . channels = bot . channels return True | The reloading magic . | 400 | 5 |
15,124 | def is_method ( arg ) : if inspect . ismethod ( arg ) : return True if isinstance ( arg , NonInstanceMethod ) : return True # Unfortunately, there is no disctinction between instance methods # that are yet to become part of a class, and regular functions. # We attempt to evade this little gray zone by relying on extremely strong # convention (which is nevertheless _not_ enforced by the intepreter) # that first argument of an instance method must be always named ``self``. if inspect . isfunction ( arg ) : return _get_first_arg_name ( arg ) == 'self' return False | Checks whether given object is a method . | 133 | 9 |
15,125 | def _ask ( self , answers ) : if isinstance ( self . validator , list ) : for v in self . validator : v . answers = answers else : self . validator . answers = answers while ( True ) : q = self . question % answers if not self . choices ( ) : logger . warn ( 'No choices were supplied for "%s"' % q ) return None if self . value in answers : default = Validator . stringify ( answers [ self . value ] ) answer = self . _get_input ( "%s [%s]: " % ( q , default ) ) if answer == '' : answer = answers [ self . value ] else : answer = self . _get_input ( "%s: " % q ) # if we are in multiple mode and the answer is just the empty # string (enter/return pressed) then we will just answer None # to indicate we are done if answer == '.' and self . multiple : return None if self . validate ( answer ) : return self . answer ( ) else : if isinstance ( self . validator , list ) : for v in self . validator : if v . error ( ) != '' : print ( v . error ( ) ) else : print ( self . validator . error ( ) ) | Really ask the question . | 270 | 5 |
15,126 | def ask ( self , answers = None ) : if answers is None : answers = { } _answers = { } if self . multiple : print ( ( bold ( 'Multiple answers are supported for this question. ' + 'Please enter a "." character to finish.' ) ) ) _answers [ self . value ] = [ ] answer = self . _ask ( answers ) while answer is not None : _answers [ self . value ] . append ( answer ) answer = self . _ask ( answers ) else : _answers [ self . value ] = self . _ask ( answers ) if isinstance ( self . validator , list ) : for v in self . validator : _answers = dict ( _answers , * * v . hints ( ) ) else : _answers = dict ( _answers , * * self . validator . hints ( ) ) for q in self . _questions : answers = dict ( answers , * * _answers ) _answers = dict ( _answers , * * q . ask ( answers ) ) return _answers | Ask the question then ask any sub - questions . | 242 | 10 |
15,127 | def answer ( self ) : if isinstance ( self . validator , list ) : return self . validator [ 0 ] . choice ( ) return self . validator . choice ( ) | Return the answer for the question from the validator . | 39 | 11 |
15,128 | def choices ( self ) : if isinstance ( self . validator , list ) : return self . validator [ 0 ] . print_choices ( ) return self . validator . print_choices ( ) | Print the choices for this question . | 45 | 7 |
15,129 | def _timing ( f , logs_every = 100 ) : @ functools . wraps ( f ) def wrap ( * args , * * kw ) : """The timer function.""" ts = _time . time ( ) result = f ( * args , * * kw ) te = _time . time ( ) qj . _call_counts [ f ] += 1 qj . _timings [ f ] += ( te - ts ) count = qj . _call_counts [ f ] if count % logs_every == 0 : qj ( x = '%2.4f seconds' % ( qj . _timings [ f ] / count ) , s = 'Average timing for %s across %d call%s' % ( f , count , '' if count == 1 else 's' ) , _depth = 2 ) return result return wrap | Decorator to time function calls and log the stats . | 188 | 12 |
15,130 | def _catch ( f , exception_type ) : if not ( inspect . isclass ( exception_type ) and issubclass ( exception_type , Exception ) ) : exception_type = Exception @ functools . wraps ( f ) def wrap ( * args , * * kw ) : try : return f ( * args , * * kw ) except exception_type as e : # pylint: disable=broad-except qj ( e , 'Caught an exception in %s' % f , d = 1 , _depth = 2 ) return wrap | Decorator to drop into the debugger if a function throws an exception . | 120 | 15 |
15,131 | def _annotate_fn_args ( stack , fn_opname , nargs , nkw = - 1 , consume_fn_name = True ) : kwarg_names = [ ] if nkw == - 1 : if sys . version_info [ 0 ] < 3 : # Compute nkw and nargs from nargs for python 2.7 nargs , nkw = ( nargs % 256 , 2 * nargs // 256 ) else : if fn_opname == 'CALL_FUNCTION_KW' : if qj . _DEBUG_QJ : assert len ( stack ) and stack [ - 1 ] . opname == 'LOAD_CONST' if not len ( stack ) or stack [ - 1 ] . opname != 'LOAD_CONST' : return se = stack . pop ( ) kwarg_names = se . oparg_repr [ : : - 1 ] se . oparg_repr = [ '' ] nkw = len ( kwarg_names ) nargs -= nkw if qj . _DEBUG_QJ : assert nargs >= 0 and nkw > 0 else : nkw = 0 for i in range ( nkw ) : se = stack . pop ( ) if se . stack_depth == 0 and ( len ( se . oparg_repr ) == 0 or se . oparg_repr [ 0 ] == '' ) : # Skip stack entries that don't have any effect on the stack continue if i % 2 == 1 and sys . version_info [ 0 ] < 3 : if qj . _DEBUG_QJ : assert se . opname == 'LOAD_CONST' if se . opname == 'LOAD_CONST' : # kwargs are pairs of key=value in code se . oparg_repr += [ '=' ] else : pops = [ ] if se . opname . startswith ( 'CALL_FUNCTION' ) : _annotate_fn_args ( stack [ : ] , se . opname , se . oparg , - 1 , True ) pops = _collect_pops ( stack , se . stack_depth - 1 if se . opname . startswith ( 'CALL_FUNCTION' ) else 0 , [ ] , False ) if i > 1 and len ( pops ) : pops [ - 1 ] . oparg_repr += [ ',' ] if sys . version_info [ 0 ] >= 3 : target_se = pops [ - 1 ] if len ( pops ) else se target_se . oparg_repr = [ kwarg_names [ i ] , '=' ] + target_se . oparg_repr for i in range ( nargs ) : se = stack . pop ( ) if se . opname . startswith ( 'CALL_FUNCTION' ) : _annotate_fn_args ( stack , se . opname , se . oparg , - 1 , True ) elif len ( se . oparg_repr ) and se . oparg_repr [ 0 ] in { ']' , '}' , ')' } : if ( i > 0 or nkw > 0 ) : se . oparg_repr += [ ',' ] else : pops = _collect_pops ( stack , se . stack_depth , [ ] , False ) if ( i > 0 or nkw > 0 ) and len ( pops ) : pops [ - 1 ] . oparg_repr += [ ',' ] if consume_fn_name : _collect_pops ( stack , - 1 , [ ] , False ) | Add commas and equals as appropriate to function argument lists in the stack . | 779 | 15 |
15,132 | def generate_mediation_matrix ( dsm ) : cat = dsm . categories ent = dsm . entities size = dsm . size [ 0 ] if not cat : cat = [ 'appmodule' ] * size packages = [ e . split ( '.' ) [ 0 ] for e in ent ] # define and initialize the mediation matrix mediation_matrix = [ [ 0 for _ in range ( size ) ] for _ in range ( size ) ] for i in range ( 0 , size ) : for j in range ( 0 , size ) : if cat [ i ] == 'framework' : if cat [ j ] == 'framework' : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'corelib' : if ( cat [ j ] in ( 'framework' , 'corelib' ) or ent [ i ] . startswith ( packages [ j ] + '.' ) or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'applib' : if ( cat [ j ] in ( 'framework' , 'corelib' , 'applib' ) or ent [ i ] . startswith ( packages [ j ] + '.' ) or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'appmodule' : # we cannot force an app module to import things from # the broker if the broker itself did not import anything if ( cat [ j ] in ( 'framework' , 'corelib' , 'applib' , 'broker' , 'data' ) or ent [ i ] . startswith ( packages [ j ] + '.' ) or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'broker' : # we cannot force the broker to import things from # app modules if there is nothing to be imported. # also broker should be authorized to use third apps if ( cat [ j ] in ( 'appmodule' , 'corelib' , 'framework' ) or ent [ i ] . startswith ( packages [ j ] + '.' ) or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 elif cat [ i ] == 'data' : if ( cat [ j ] == 'framework' or i == j ) : mediation_matrix [ i ] [ j ] = - 1 else : mediation_matrix [ i ] [ j ] = 0 else : # mediation_matrix[i][j] = -2 # errors in the generation raise DesignStructureMatrixError ( 'Mediation matrix value NOT generated for %s:%s' % ( i , j ) ) return mediation_matrix | Generate the mediation matrix of the given matrix . | 668 | 10 |
15,133 | def check ( self , dsm , simplicity_factor = 2 , * * kwargs ) : # economy_of_mechanism economy_of_mechanism = False message = '' data = dsm . data categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size dependency_number = 0 # evaluate Matrix(data) for i in range ( 0 , dsm_size ) : for j in range ( 0 , dsm_size ) : if ( categories [ i ] not in ( 'framework' , 'corelib' ) and categories [ j ] not in ( 'framework' , 'corelib' ) and data [ i ] [ j ] > 0 ) : dependency_number += 1 # check comparison result if dependency_number < dsm_size * simplicity_factor : economy_of_mechanism = True else : message = ' ' . join ( [ 'Number of dependencies (%s)' % dependency_number , '> number of rows (%s)' % dsm_size , '* simplicity factor (%s) = %s' % ( simplicity_factor , dsm_size * simplicity_factor ) ] ) return economy_of_mechanism , message | Check economy of mechanism . | 272 | 5 |
15,134 | def check ( self , dsm , independence_factor = 5 , * * kwargs ) : # leastCommonMechanismMatrix least_common_mechanism = False message = '' # get the list of dependent modules for each module data = dsm . data categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size dependent_module_number = [ ] # evaluate Matrix(data) for j in range ( 0 , dsm_size ) : dependent_module_number . append ( 0 ) for i in range ( 0 , dsm_size ) : if ( categories [ i ] != 'framework' and categories [ j ] != 'framework' and data [ i ] [ j ] > 0 ) : dependent_module_number [ j ] += 1 # except for the broker if any and libs, check that threshold is not # overlapped # index of brokers # and app_libs are set to 0 for index , item in enumerate ( dsm . categories ) : if item == 'broker' or item == 'applib' : dependent_module_number [ index ] = 0 if max ( dependent_module_number ) <= dsm_size / independence_factor : least_common_mechanism = True else : maximum = max ( dependent_module_number ) message = ( 'Dependencies to %s (%s) > matrix size (%s) / ' 'independence factor (%s) = %s' % ( dsm . entities [ dependent_module_number . index ( maximum ) ] , maximum , dsm_size , independence_factor , dsm_size / independence_factor ) ) return least_common_mechanism , message | Check least common mechanism . | 374 | 5 |
15,135 | def check ( self , dsm , * * kwargs ) : layered_architecture = True messages = [ ] categories = dsm . categories dsm_size = dsm . size [ 0 ] if not categories : categories = [ 'appmodule' ] * dsm_size for i in range ( 0 , dsm_size - 1 ) : for j in range ( i + 1 , dsm_size ) : if ( categories [ i ] != 'broker' and categories [ j ] != 'broker' and dsm . entities [ i ] . split ( '.' ) [ 0 ] != dsm . entities [ j ] . split ( '.' ) [ 0 ] ) : # noqa if dsm . data [ i ] [ j ] > 0 : layered_architecture = False messages . append ( 'Dependency from %s to %s breaks the ' 'layered architecture.' % ( dsm . entities [ i ] , dsm . entities [ j ] ) ) return layered_architecture , '\n' . join ( messages ) | Check layered architecture . | 229 | 4 |
15,136 | def check ( self , dsm , * * kwargs ) : logger . debug ( 'Entities = %s' % dsm . entities ) messages = [ ] code_clean = True threshold = kwargs . pop ( 'threshold' , 1 ) rows , _ = dsm . size for i in range ( 0 , rows ) : if dsm . data [ i ] [ 0 ] > threshold : messages . append ( 'Number of issues (%d) in module %s ' '> threshold (%d)' % ( dsm . data [ i ] [ 0 ] , dsm . entities [ i ] , threshold ) ) code_clean = False return code_clean , '\n' . join ( messages ) | Check code clean . | 153 | 4 |
15,137 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( 'date' , nargs = '*' , action = arguments . DateParser ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return if not cmdargs . date : send ( "Time until when?" ) return delta = dateutil . relativedelta . relativedelta ( cmdargs . date , datetime . datetime . now ( ) ) diff = "%s is " % cmdargs . date . strftime ( "%x" ) if delta . years : diff += "%d years " % ( delta . years ) if delta . months : diff += "%d months " % ( delta . months ) if delta . days : diff += "%d days " % ( delta . days ) if delta . hours : diff += "%d hours " % ( delta . hours ) if delta . minutes : diff += "%d minutes " % ( delta . minutes ) if delta . seconds : diff += "%d seconds " % ( delta . seconds ) diff += "away" send ( diff ) | Reports the difference between now and some specified time . | 251 | 10 |
15,138 | def abstract ( class_ ) : if not inspect . isclass ( class_ ) : raise TypeError ( "@abstract can only be applied to classes" ) abc_meta = None # if the class is not already using a metaclass specific to ABC, # we need to change that class_meta = type ( class_ ) if class_meta not in ( _ABCMetaclass , _ABCObjectMetaclass ) : # decide what metaclass to use, depending on whether it's a subclass # of our universal :class:`Object` or not if class_meta is type : abc_meta = _ABCMetaclass # like ABCMeta, but can never instantiate elif class_meta is ObjectMetaclass : abc_meta = _ABCObjectMetaclass # ABCMeta mixed with ObjectMetaclass else : raise ValueError ( "@abstract cannot be applied to classes with custom metaclass" ) class_ . __abstract__ = True return metaclass ( abc_meta ) ( class_ ) if abc_meta else class_ | Mark the class as _abstract_ base class forbidding its instantiation . | 229 | 16 |
15,139 | def final ( arg ) : if inspect . isclass ( arg ) : if not isinstance ( arg , ObjectMetaclass ) : raise ValueError ( "@final can only be applied to a class " "that is a subclass of Object" ) elif not is_method ( arg ) : raise TypeError ( "@final can only be applied to classes or methods" ) method = arg . method if isinstance ( arg , _WrappedMethod ) else arg method . __final__ = True return arg | Mark a class or method as _final_ . | 104 | 10 |
15,140 | def override ( base = ABSENT ) : arg = base # ``base`` is just for clean, user-facing argument name # direct application of the modifier through ``@override`` if inspect . isfunction ( arg ) or isinstance ( arg , NonInstanceMethod ) : _OverrideDecorator . maybe_signal_classmethod ( arg ) decorator = _OverrideDecorator ( None ) return decorator ( arg ) # indirect (but simple) application of the modifier through ``@override()`` if arg is ABSENT : return _OverrideDecorator ( None ) # full-blown application, with base class specified if is_class ( arg ) or is_string ( arg ) : return _OverrideDecorator ( arg ) raise TypeError ( "explicit base class for @override " "must be either a string or a class object" ) | Mark a method as overriding a corresponding method from superclass . | 182 | 12 |
15,141 | def find ( * args , * * kwargs ) : list_ , idx = _index ( * args , start = 0 , step = 1 , * * kwargs ) if idx < 0 : raise IndexError ( "element not found" ) return list_ [ idx ] | Find the first matching element in a list and return it . | 62 | 12 |
15,142 | def findlast ( * args , * * kwargs ) : list_ , idx = _index ( * args , start = sys . maxsize , step = - 1 , * * kwargs ) if idx < 0 : raise IndexError ( "element not found" ) return list_ [ idx ] | Find the last matching element in a list and return it . | 67 | 12 |
15,143 | def index ( * args , * * kwargs ) : _ , idx = _index ( * args , start = 0 , step = 1 , * * kwargs ) return idx | Search a list for an exact element or element satisfying a predicate . | 41 | 13 |
15,144 | def lastindex ( * args , * * kwargs ) : _ , idx = _index ( * args , start = sys . maxsize , step = - 1 , * * kwargs ) return idx | Search a list backwards for an exact element or element satisfying a predicate . | 46 | 14 |
15,145 | def _index ( * args , * * kwargs ) : start = kwargs . pop ( 'start' , 0 ) step = kwargs . pop ( 'step' , 1 ) if len ( args ) == 2 : elem , list_ = args ensure_sequence ( list_ ) predicate = lambda item : item == elem else : ensure_keyword_args ( kwargs , mandatory = ( 'in_' , ) , optional = ( 'of' , 'where' ) ) if 'of' in kwargs and 'where' in kwargs : raise TypeError ( "either an item or predicate must be supplied, not both" ) if not ( 'of' in kwargs or 'where' in kwargs ) : raise TypeError ( "an item or predicate must be supplied" ) list_ = ensure_sequence ( kwargs [ 'in_' ] ) if 'where' in kwargs : predicate = ensure_callable ( kwargs [ 'where' ] ) else : elem = kwargs [ 'of' ] predicate = lambda item : item == elem len_ = len ( list_ ) start = max ( 0 , min ( len_ - 1 , start ) ) i = start while 0 <= i < len_ : if predicate ( list_ [ i ] ) : return list_ , i i += step else : return list_ , - 1 | Implementation of list searching . | 302 | 6 |
15,146 | def intercalate ( elems , list_ ) : ensure_sequence ( elems ) ensure_sequence ( list_ ) if len ( list_ ) <= 1 : return list_ return sum ( ( elems + list_ [ i : i + 1 ] for i in xrange ( 1 , len ( list_ ) ) ) , list_ [ : 1 ] ) | Insert given elements between existing elements of a list . | 77 | 10 |
15,147 | def handle ( _ , msg , args ) : # SHUT CAPS LOCK OFF, MORON if args [ 'config' ] [ 'feature' ] . getboolean ( 'capskick' ) : nick = args [ 'nick' ] threshold = 0.65 text = "shutting caps lock off" upper = [ i for i in msg if i in string . ascii_uppercase ] if len ( msg ) == 0 : return upper_ratio = len ( upper ) / len ( msg . replace ( ' ' , '' ) ) if args [ 'target' ] != 'private' : with _caps_lock : if upper_ratio > threshold and len ( msg ) > 10 : if nick in _caps : args [ 'do_kick' ] ( args [ 'target' ] , nick , text ) _caps . remove ( nick ) else : _caps . append ( nick ) elif nick in _caps : _caps . remove ( nick ) | Check for capslock abuse . | 207 | 6 |
15,148 | def cmd ( send , msg , args ) : if not msg : msg = gen_word ( ) send ( gen_fullwidth ( msg . upper ( ) ) ) | Converts text to fullwidth characters . | 35 | 8 |
15,149 | def task_estimates ( channel , states ) : for state in states : if state != task_states . OPEN : raise NotImplementedError ( 'only estimate OPEN tasks' ) tasks = yield channel . tasks ( state = states ) # Estimate all the unique packages. packages = set ( [ task . package for task in tasks ] ) print ( 'checking avg build duration for %i packages:' % len ( packages ) ) packages = list ( packages ) durations = yield average_build_durations ( channel . connection , packages ) avg_package_durations = dict ( zip ( packages , durations ) ) # pprint(avg_package_durations) # Determine estimates for all our tasks. results = [ ] utcnow = datetime . utcnow ( ) for task in tasks : avg_duration = avg_package_durations [ task . package ] est_complete = task . started + avg_duration est_remaining = est_complete - utcnow result = ( task , est_remaining ) results . append ( result ) defer . returnValue ( results ) | Estimate remaining time for all tasks in this channel . | 233 | 11 |
15,150 | def describe_delta ( delta ) : s = delta . total_seconds ( ) s = abs ( s ) hours , remainder = divmod ( s , 3600 ) minutes , seconds = divmod ( remainder , 60 ) if hours : return '%d hr %d min' % ( hours , minutes ) if minutes : return '%d min %d secs' % ( minutes , seconds ) return '%d secs' % seconds | Describe this timedelta in human - readable terms . | 93 | 11 |
15,151 | def log_est_complete ( est_complete ) : if not est_complete : print ( 'could not determine an estimated completion time' ) return remaining = est_complete - datetime . utcnow ( ) message = 'this task should be complete in %s' if remaining . total_seconds ( ) < 0 : message = 'this task exceeds estimate by %s' log_delta ( message , remaining ) | Log the relative time remaining for this est_complete datetime object . | 88 | 14 |
15,152 | def patched_normalizeargs ( sequence , output = None ) : if output is None : output = [ ] if Broken in getattr ( sequence , '__bases__' , ( ) ) : return [ sequence ] cls = sequence . __class__ if InterfaceClass in cls . __mro__ or zope . interface . declarations . Implements in cls . __mro__ : output . append ( sequence ) else : for v in sequence : patched_normalizeargs ( v , output ) return output | Normalize declaration arguments | 112 | 4 |
15,153 | def profiles ( ) : paths = [ ] for pattern in PROFILES : pattern = os . path . expanduser ( pattern ) paths += glob ( pattern ) return paths | List of all the connection profile files ordered by preference . | 36 | 11 |
15,154 | def lookup ( self , profile , setting ) : for path in profiles ( ) : cfg = SafeConfigParser ( ) cfg . read ( path ) if profile not in cfg . sections ( ) : continue if not cfg . has_option ( profile , setting ) : continue return cfg . get ( profile , setting ) | Check koji . conf . d files for this profile s setting . | 69 | 14 |
15,155 | def connect_from_web ( klass , url ) : # Treat any input with whitespace as invalid: if re . search ( r'\s' , url ) : return url = url . split ( ' ' , 1 ) [ 0 ] for path in profiles ( ) : cfg = SafeConfigParser ( ) cfg . read ( path ) for profile in cfg . sections ( ) : if not cfg . has_option ( profile , 'weburl' ) : continue weburl = cfg . get ( profile , 'weburl' ) if url . startswith ( weburl ) : return klass ( profile ) | Find a connection that matches this kojiweb URL . | 136 | 11 |
15,156 | def from_web ( self , url ) : # Treat any input with whitespace as invalid: if re . search ( r'\s' , url ) : return defer . succeed ( None ) o = urlparse ( url ) endpoint = os . path . basename ( o . path ) if o . query : query = parse_qs ( o . query ) # Known Kojiweb endpoints: endpoints = { 'buildinfo' : ( 'buildID' , self . getBuild ) , 'channelinfo' : ( 'channelID' , self . getChannel ) , 'hostinfo' : ( 'hostID' , self . getHost ) , 'packageinfo' : ( 'packageID' , self . getPackage ) , 'taskinfo' : ( 'taskID' , self . getTaskInfo ) , 'taginfo' : ( 'tagID' , self . getTag ) , 'targetinfo' : ( 'targetID' , self . getTarget ) , 'userinfo' : ( 'userID' , self . getUser ) , } try : ( param , method ) = endpoints [ endpoint ] except KeyError : return defer . succeed ( None ) try : id_str = query [ param ] [ 0 ] id_ = int ( id_str ) except ( KeyError , ValueError ) : return defer . succeed ( None ) return method ( id_ ) | Reverse - engineer a kojiweb URL into an equivalent API response . | 294 | 16 |
15,157 | def call ( self , method , * args , * * kwargs ) : if kwargs : kwargs [ '__starstar' ] = True args = args + ( kwargs , ) if self . session_id : self . proxy . path = self . _authenticated_path ( ) d = self . proxy . callRemote ( method , * args ) d . addCallback ( self . _munchify_callback ) d . addErrback ( self . _parse_errback ) if self . callnum is not None : self . callnum += 1 return d | Make an XML - RPC call to the server . | 126 | 10 |
15,158 | def _authenticated_path ( self ) : basepath = self . proxy . path . decode ( ) . split ( '?' ) [ 0 ] params = urlencode ( { 'session-id' : self . session_id , 'session-key' : self . session_key , 'callnum' : self . callnum } ) result = '%s?%s' % ( basepath , params ) return result . encode ( 'utf-8' ) | Get the path of our XML - RPC endpoint with session auth params added . | 102 | 15 |
15,159 | def getAverageBuildDuration ( self , package , * * kwargs ) : seconds = yield self . call ( 'getAverageBuildDuration' , package , * * kwargs ) if seconds is None : defer . returnValue ( None ) defer . returnValue ( timedelta ( seconds = seconds ) ) | Return a timedelta that Koji considers to be average for this package . | 64 | 15 |
15,160 | def getBuild ( self , build_id , * * kwargs ) : buildinfo = yield self . call ( 'getBuild' , build_id , * * kwargs ) build = Build . fromDict ( buildinfo ) if build : build . connection = self defer . returnValue ( build ) | Load all information about a build and return a custom Build class . | 66 | 13 |
15,161 | def getChannel ( self , channel_id , * * kwargs ) : channelinfo = yield self . call ( 'getChannel' , channel_id , * * kwargs ) channel = Channel . fromDict ( channelinfo ) if channel : channel . connection = self defer . returnValue ( channel ) | Load all information about a channel and return a custom Channel class . | 66 | 13 |
15,162 | def getPackage ( self , name , * * kwargs ) : packageinfo = yield self . call ( 'getPackage' , name , * * kwargs ) package = Package . fromDict ( packageinfo ) if package : package . connection = self defer . returnValue ( package ) | Load information about a package and return a custom Package class . | 62 | 12 |
15,163 | def getTaskDescendents ( self , task_id , * * kwargs ) : kwargs [ 'request' ] = True data = yield self . call ( 'getTaskDescendents' , task_id , * * kwargs ) tasks = [ ] for tdata in data [ str ( task_id ) ] : task = Task . fromDict ( tdata ) task . connection = self tasks . append ( task ) defer . returnValue ( tasks ) | Load all information about a task s descendents into Task classes . | 102 | 13 |
15,164 | def getTaskInfo ( self , task_id , * * kwargs ) : kwargs [ 'request' ] = True taskinfo = yield self . call ( 'getTaskInfo' , task_id , * * kwargs ) task = Task . fromDict ( taskinfo ) if task : task . connection = self defer . returnValue ( task ) | Load all information about a task and return a custom Task class . | 78 | 13 |
15,165 | def listBuilds ( self , package , * * kwargs ) : if isinstance ( package , int ) : package_id = package else : package_data = yield self . getPackage ( package ) if package_data is None : defer . returnValue ( [ ] ) package_id = package_data . id data = yield self . call ( 'listBuilds' , package_id , * * kwargs ) builds = [ ] for bdata in data : build = Build . fromDict ( bdata ) build . connection = self builds . append ( build ) defer . returnValue ( builds ) | Get information about all builds of a package . | 130 | 9 |
15,166 | def listTagged ( self , * args , * * kwargs ) : data = yield self . call ( 'listTagged' , * args , * * kwargs ) builds = [ ] for bdata in data : build = Build . fromDict ( bdata ) build . connection = self builds . append ( build ) defer . returnValue ( builds ) | List builds tagged with a tag . | 78 | 7 |
15,167 | def listTasks ( self , opts = { } , queryOpts = { } ) : opts [ 'decode' ] = True # decode xmlrpc data in "request" data = yield self . call ( 'listTasks' , opts , queryOpts ) tasks = [ ] for tdata in data : task = Task . fromDict ( tdata ) task . connection = self tasks . append ( task ) defer . returnValue ( tasks ) | Get information about all Koji tasks . | 100 | 8 |
15,168 | def listChannels ( self , * * kwargs ) : data = yield self . call ( 'listChannels' , * * kwargs ) channels = [ ] for cdata in data : channel = Channel . fromDict ( cdata ) channel . connection = self channels . append ( channel ) defer . returnValue ( channels ) | Get information about all Koji channels . | 72 | 8 |
15,169 | def login ( self ) : authtype = self . lookup ( self . profile , 'authtype' ) if authtype is None : cert = self . lookup ( self . profile , 'cert' ) if cert and os . path . isfile ( os . path . expanduser ( cert ) ) : authtype = 'ssl' # Note: official koji cli is a little more lax here. If authtype is # None and we have a valid kerberos ccache, we still try kerberos # auth. if authtype == 'kerberos' : # Note: we don't try the old-style kerberos login here. result = yield self . _gssapi_login ( ) elif authtype == 'ssl' : result = yield self . _ssl_login ( ) else : raise NotImplementedError ( 'unsupported auth: %s' % authtype ) self . session_id = result [ 'session-id' ] self . session_key = result [ 'session-key' ] self . callnum = 0 # increment this on every call for this session. defer . returnValue ( True ) | Return True if we successfully logged into this Koji hub . | 242 | 12 |
15,170 | def _ssl_agent ( self ) : # Load "cert" into a PrivateCertificate. certfile = self . lookup ( self . profile , 'cert' ) certfile = os . path . expanduser ( certfile ) with open ( certfile ) as certfp : pemdata = certfp . read ( ) client_cert = PrivateCertificate . loadPEM ( pemdata ) trustRoot = None # Use Twisted's platformTrust(). # Optionally load "serverca" into a Certificate. servercafile = self . lookup ( self . profile , 'serverca' ) if servercafile : servercafile = os . path . expanduser ( servercafile ) trustRoot = RootCATrustRoot ( servercafile ) policy = ClientCertPolicy ( trustRoot = trustRoot , client_cert = client_cert ) return Agent ( reactor , policy ) | Get a Twisted Agent that performs Client SSL authentication for Koji . | 189 | 13 |
15,171 | def _get_bmdl_ratio ( self , models ) : bmdls = [ model . output [ "BMDL" ] for model in models if model . output [ "BMDL" ] > 0 ] return max ( bmdls ) / min ( bmdls ) if len ( bmdls ) > 0 else 0 | Return BMDL ratio in list of models . | 72 | 10 |
15,172 | def _get_parsimonious_model ( models ) : params = [ len ( model . output [ "parameters" ] ) for model in models ] idx = params . index ( min ( params ) ) return models [ idx ] | Return the most parsimonious model of all available models . The most parsimonious model is defined as the model with the fewest number of parameters . | 52 | 31 |
15,173 | def make_pathable_string ( s , replacewith = '_' ) : import re return re . sub ( r'[^\w+/.]' , replacewith , s . lower ( ) ) | Removes symbols from a string to be compatible with directory structure . | 49 | 13 |
15,174 | def get_time ( ) : import datetime time = make_pathable_string ( '%s' % datetime . datetime . now ( ) ) return time . replace ( '-' , '_' ) . replace ( ':' , '_' ) . replace ( '.' , '_' ) | Gets current time in a form of a formated string . Used in logger function . | 66 | 18 |
15,175 | def bootstrap_general_election ( self , election ) : election_day = election . election_day page_type , created = PageType . objects . get_or_create ( model_type = ContentType . objects . get ( app_label = "election" , model = "electionday" ) , election_day = election_day , ) PageContent . objects . get_or_create ( content_type = ContentType . objects . get_for_model ( page_type ) , object_id = page_type . pk , election_day = election_day , ) | Create a general election page type | 126 | 6 |
15,176 | def cmd ( send , msg , _ ) : try : answer = subprocess . check_output ( [ 'wtf' , msg ] , stderr = subprocess . STDOUT ) send ( answer . decode ( ) . strip ( ) . replace ( '\n' , ' or ' ) . replace ( 'fuck' , 'fsck' ) ) except subprocess . CalledProcessError as ex : send ( ex . output . decode ( ) . rstrip ( ) . splitlines ( ) [ 0 ] ) | Tells you what acronyms mean . | 109 | 9 |
15,177 | def sys ( * * kwargs ) : output , err = cli_syncthing_adapter . sys ( * * kwargs ) if output : click . echo ( "%s" % output , err = err ) else : if not kwargs [ 'init' ] : click . echo ( click . get_current_context ( ) . get_help ( ) ) | Manage system configuration . | 82 | 5 |
15,178 | def ls ( ) : heading , body = cli_syncthing_adapter . ls ( ) if heading : click . echo ( heading ) if body : click . echo ( body . strip ( ) ) | List all synchronized directories . | 44 | 5 |
15,179 | def auth ( * * kwargs ) : """ kodrive auth <path> <device_id (client)> 1. make sure path has been added to config.xml, server 2. make sure path is not shared by someone 3. add device_id to folder in config.xml, server 4. add device to devices in config.xml, server """ option = 'add' path = kwargs [ 'path' ] key = kwargs [ 'key' ] if kwargs [ 'remove' ] : option = 'remove' if kwargs [ 'yes' ] : output , err = cli_syncthing_adapter . auth ( option , key , path ) click . echo ( "%s" % output , err = err ) else : verb = 'authorize' if not kwargs [ 'remove' ] else 'de-authorize' if click . confirm ( "Are you sure you want to %s this device to access %s?" % ( verb , path ) ) : output , err = cli_syncthing_adapter . auth ( option , key , path ) if output : click . echo ( "%s" % output , err = err ) | Authorize device synchronization . | 256 | 5 |
15,180 | def mv ( source , target ) : if os . path . isfile ( target ) and len ( source ) == 1 : if click . confirm ( "Are you sure you want to overwrite %s?" % target ) : err_msg = cli_syncthing_adapter . mv_edge_case ( source , target ) # Edge case: to match Bash 'mv' behavior and overwrite file if err_msg : click . echo ( err_msg ) return if len ( source ) > 1 and not os . path . isdir ( target ) : click . echo ( click . get_current_context ( ) . get_help ( ) ) return else : err_msg , err = cli_syncthing_adapter . mv ( source , target ) if err_msg : click . echo ( err_msg , err ) | Move synchronized directory . | 181 | 4 |
15,181 | def push ( * * kwargs ) : output , err = cli_syncthing_adapter . refresh ( * * kwargs ) if output : click . echo ( "%s" % output , err = err ) if kwargs [ 'verbose' ] and not err : with click . progressbar ( iterable = None , length = 100 , label = 'Synchronizing' ) as bar : device_num = 0 max_devices = 1 prev_percent = 0 while True : kwargs [ 'progress' ] = True kwargs [ 'device_num' ] = device_num data , err = cli_syncthing_adapter . refresh ( * * kwargs ) device_num = data [ 'device_num' ] max_devices = data [ 'max_devices' ] cur_percent = math . floor ( data [ 'percent' ] ) - prev_percent if cur_percent > 0 : bar . update ( cur_percent ) prev_percent = math . floor ( data [ 'percent' ] ) if device_num < max_devices : time . sleep ( 0.5 ) else : break | Force synchronization of directory . | 246 | 5 |
15,182 | def tag ( path , name ) : output , err = cli_syncthing_adapter . tag ( path , name ) click . echo ( "%s" % output , err = err ) | Change tag associated with directory . | 42 | 6 |
15,183 | def free ( * * kwargs ) : output , err = cli_syncthing_adapter . free ( kwargs [ 'path' ] ) click . echo ( "%s" % output , err = err ) | Stop synchronization of directory . | 49 | 5 |
15,184 | def add ( * * kwargs ) : output , err = cli_syncthing_adapter . add ( * * kwargs ) click . echo ( "%s" % output , err = err ) | Make a directory shareable . | 46 | 6 |
15,185 | def info ( path ) : output , err = cli_syncthing_adapter . info ( folder = path ) if err : click . echo ( output , err = err ) else : stat = output [ 'status' ] click . echo ( "State: %s" % stat [ 'state' ] ) click . echo ( "\nTotal Files: %s" % stat [ 'localFiles' ] ) click . echo ( "Files Needed: %s" % stat [ 'needFiles' ] ) click . echo ( "\nTotal Bytes: %s" % stat [ 'localBytes' ] ) click . echo ( "Bytes Needed: %s" % stat [ 'needBytes' ] ) progress = output [ 'files_needed' ] [ 'progress' ] queued = output [ 'files_needed' ] [ 'queued' ] rest = output [ 'files_needed' ] [ 'rest' ] if len ( progress ) or len ( queued ) or len ( rest ) : click . echo ( "\nFiles Needed:" ) for f in progress : click . echo ( " " + f [ 'name' ] ) for f in queued : click . echo ( " " + f [ 'name' ] ) for f in rest : click . echo ( " " + f [ 'name' ] ) click . echo ( "\nDevices Authorized:\n%s" % output [ 'auth_ls' ] ) | Display synchronization information . | 310 | 4 |
15,186 | def key ( * * kwargs ) : output , err = cli_syncthing_adapter . key ( device = True ) click . echo ( "%s" % output , err = err ) | Display system key . | 44 | 4 |
15,187 | def start ( * * kwargs ) : output , err = cli_syncthing_adapter . start ( * * kwargs ) click . echo ( "%s" % output , err = err ) | Start KodeDrive daemon . | 46 | 6 |
15,188 | def stop ( ) : output , err = cli_syncthing_adapter . sys ( exit = True ) click . echo ( "%s" % output , err = err ) | Stop KodeDrive daemon . | 39 | 6 |
15,189 | def start_poll ( args ) : if args . type == 'privmsg' : return "We don't have secret ballots in this benevolent dictatorship!" if not args . msg : return "Polls need a question." ctrlchan = args . config [ 'core' ] [ 'ctrlchan' ] poll = Polls ( question = args . msg , submitter = args . nick ) args . session . add ( poll ) args . session . flush ( ) if args . isadmin or not args . config . getboolean ( 'adminrestrict' , 'poll' ) : poll . accepted = 1 return "Poll #%d created!" % poll . id else : args . send ( "Poll submitted for approval." , target = args . nick ) args . send ( "New Poll: #%d -- %s, Submitted by %s" % ( poll . id , args . msg , args . nick ) , target = ctrlchan ) return "" | Starts a poll . | 202 | 5 |
15,190 | def delete_poll ( args ) : if not args . isadmin : return "Nope, not gonna do it." if not args . msg : return "Syntax: !poll delete <pollnum>" if not args . msg . isdigit ( ) : return "Not A Valid Positive Integer." poll = args . session . query ( Polls ) . filter ( Polls . accepted == 1 , Polls . id == int ( args . msg ) ) . first ( ) if poll is None : return "Poll does not exist." if poll . active == 1 : return "You can't delete an active poll!" elif poll . deleted == 1 : return "Poll already deleted." poll . deleted = 1 return "Poll deleted." | Deletes a poll . | 152 | 5 |
15,191 | def edit_poll ( args ) : if not args . isadmin : return "Nope, not gonna do it." msg = args . msg . split ( maxsplit = 1 ) if len ( msg ) < 2 : return "Syntax: !vote edit <pollnum> <question>" if not msg [ 0 ] . isdigit ( ) : return "Not A Valid Positive Integer." pid = int ( msg [ 0 ] ) poll = get_open_poll ( args . session , pid ) if poll is None : return "That poll was deleted or does not exist!" poll . question = msg [ 1 ] return "Poll updated!" | Edits a poll . | 133 | 5 |
15,192 | def reopen ( args ) : if not args . isadmin : return "Nope, not gonna do it." msg = args . msg . split ( ) if not msg : return "Syntax: !poll reopen <pollnum>" if not msg [ 0 ] . isdigit ( ) : return "Not a valid positve integer." pid = int ( msg [ 0 ] ) poll = get_open_poll ( args . session , pid ) if poll is None : return "That poll doesn't exist or has been deleted!" poll . active = 1 return "Poll %d reopened!" % pid | reopens a closed poll . | 123 | 6 |
15,193 | def end_poll ( args ) : if not args . isadmin : return "Nope, not gonna do it." if not args . msg : return "Syntax: !vote end <pollnum>" if not args . msg . isdigit ( ) : return "Not A Valid Positive Integer." poll = get_open_poll ( args . session , int ( args . msg ) ) if poll is None : return "That poll doesn't exist or has already been deleted!" if poll . active == 0 : return "Poll already ended!" poll . active = 0 return "Poll ended!" | Ends a poll . | 122 | 5 |
15,194 | def tally_poll ( args ) : if not args . msg : return "Syntax: !vote tally <pollnum>" if not args . msg . isdigit ( ) : return "Not A Valid Positive Integer." pid = int ( args . msg ) poll = get_open_poll ( args . session , pid ) if poll is None : return "That poll doesn't exist or was deleted. Use !poll list to see valid polls" state = "Active" if poll . active == 1 else "Closed" votes = args . session . query ( Poll_responses ) . filter ( Poll_responses . pid == pid ) . all ( ) args . send ( "%s poll: %s, %d total votes" % ( state , poll . question , len ( votes ) ) ) votemap = collections . defaultdict ( list ) for v in votes : votemap [ v . response ] . append ( v . voter ) for x in sorted ( votemap . keys ( ) ) : args . send ( "%s: %d -- %s" % ( x , len ( votemap [ x ] ) , ", " . join ( votemap [ x ] ) ) , target = args . nick ) if not votemap : return "" ranking = collections . defaultdict ( list ) for x in votemap . keys ( ) : num = len ( votemap [ x ] ) ranking [ num ] . append ( x ) high = max ( ranking ) winners = ( ranking [ high ] , high ) if len ( winners [ 0 ] ) == 1 : winners = ( winners [ 0 ] [ 0 ] , high ) return "The winner is %s with %d votes." % winners else : winners = ( ", " . join ( winners [ 0 ] ) , high ) return "Tie between %s with %d votes." % winners | Shows the results of poll . | 393 | 7 |
15,195 | def vote ( session , nick , pid , response ) : if not response : return "You have to vote something!" if response == "n" or response == "nay" : response = "no" elif response == "y" or response == "aye" : response = "yes" poll = get_open_poll ( session , pid ) if poll is None : return "That poll doesn't exist or isn't active. Use !poll list to see valid polls" old_vote = get_response ( session , pid , nick ) if old_vote is None : session . add ( Poll_responses ( pid = pid , response = response , voter = nick ) ) return "%s voted %s." % ( nick , response ) else : if response == old_vote . response : return "You've already voted %s." % response else : msg = "%s changed their vote from %s to %s." % ( nick , old_vote . response , response ) old_vote . response = response return msg | Votes on a poll . | 215 | 6 |
15,196 | def retract ( args ) : if not args . msg : return "Syntax: !vote retract <pollnum>" if not args . msg . isdigit ( ) : return "Not A Valid Positive Integer." response = get_response ( args . session , args . msg , args . nick ) if response is None : return "You haven't voted on that poll yet!" args . session . delete ( response ) return "Vote retracted" | Deletes a vote for a poll . | 90 | 8 |
15,197 | def cmd ( send , msg , args ) : command = msg . split ( ) msg = " " . join ( command [ 1 : ] ) if not command : send ( "Which poll?" ) return else : command = command [ 0 ] # FIXME: integrate this with ArgParser if command . isdigit ( ) : if args [ 'type' ] == 'privmsg' : send ( "We don't have secret ballots in this benevolent dictatorship!" ) else : send ( vote ( args [ 'db' ] , args [ 'nick' ] , int ( command ) , msg ) ) return isadmin = args [ 'is_admin' ] ( args [ 'nick' ] ) parser = arguments . ArgParser ( args [ 'config' ] ) parser . set_defaults ( session = args [ 'db' ] , msg = msg , nick = args [ 'nick' ] ) subparser = parser . add_subparsers ( ) start_parser = subparser . add_parser ( 'start' , config = args [ 'config' ] , aliases = [ 'open' , 'add' , 'create' ] ) start_parser . set_defaults ( func = start_poll , send = send , isadmin = isadmin , type = args [ 'type' ] ) tally_parser = subparser . add_parser ( 'tally' ) tally_parser . set_defaults ( func = tally_poll , send = send ) list_parser = subparser . add_parser ( 'list' , config = args [ 'config' ] ) list_parser . set_defaults ( func = list_polls ) retract_parser = subparser . add_parser ( 'retract' ) retract_parser . set_defaults ( func = retract ) end_parser = subparser . add_parser ( 'end' , aliases = [ 'close' ] ) end_parser . set_defaults ( func = end_poll , isadmin = isadmin ) delete_parser = subparser . add_parser ( 'delete' ) delete_parser . set_defaults ( func = delete_poll , isadmin = isadmin ) edit_parser = subparser . add_parser ( 'edit' ) edit_parser . set_defaults ( func = edit_poll , isadmin = isadmin ) reopen_parser = subparser . add_parser ( 'reopen' ) reopen_parser . set_defaults ( func = reopen , isadmin = isadmin ) try : cmdargs = parser . parse_args ( command ) except arguments . ArgumentException as e : send ( str ( e ) ) return send ( cmdargs . func ( cmdargs ) ) | Handles voting . | 568 | 4 |
15,198 | def cmd ( send , msg , args ) : parser = arguments . ArgParser ( args [ 'config' ] ) group = parser . add_mutually_exclusive_group ( ) group . add_argument ( '--high' , action = 'store_true' ) group . add_argument ( '--low' , action = 'store_true' ) group . add_argument ( '--userhigh' , action = 'store_true' ) group . add_argument ( '--nick' , action = arguments . NickParser ) group . add_argument ( 'command' , nargs = '?' ) try : cmdargs = parser . parse_args ( msg ) except arguments . ArgumentException as e : send ( str ( e ) ) return session = args [ 'db' ] totals = get_command_totals ( session ) sortedtotals = sorted ( totals , key = totals . get ) if command_registry . is_registered ( cmdargs . command ) : send ( get_command ( session , cmdargs . command , totals ) ) elif cmdargs . command and not command_registry . is_registered ( cmdargs . command ) : send ( "Command %s not found." % cmdargs . command ) elif cmdargs . high : send ( 'Most Used Commands:' ) high = list ( reversed ( sortedtotals ) ) for x in range ( 3 ) : if x < len ( high ) : send ( "%s: %s" % ( high [ x ] , totals [ high [ x ] ] ) ) elif cmdargs . low : send ( 'Least Used Commands:' ) low = sortedtotals for x in range ( 3 ) : if x < len ( low ) : send ( "%s: %s" % ( low [ x ] , totals [ low [ x ] ] ) ) elif cmdargs . userhigh : totals = get_nick_totals ( session ) sortedtotals = sorted ( totals , key = totals . get ) high = list ( reversed ( sortedtotals ) ) send ( 'Most active bot users:' ) for x in range ( 3 ) : if x < len ( high ) : send ( "%s: %s" % ( high [ x ] , totals [ high [ x ] ] ) ) elif cmdargs . nick : send ( get_nick ( session , cmdargs . nick ) ) else : command = choice ( list ( totals . keys ( ) ) ) send ( "%s has been used %s times." % ( command , totals [ command ] ) ) | Gets stats . | 546 | 4 |
15,199 | def _create_page ( cls , page , lang , auto_title , cms_app = None , parent = None , namespace = None , site = None , set_home = False ) : from cms . api import create_page , create_title from cms . utils . conf import get_templates default_template = get_templates ( ) [ 0 ] [ 0 ] if page is None : page = create_page ( auto_title , language = lang , parent = parent , site = site , template = default_template , in_navigation = True , published = True ) page . application_urls = cms_app page . application_namespace = namespace page . save ( ) page . publish ( lang ) elif lang not in page . get_languages ( ) : create_title ( language = lang , title = auto_title , page = page ) page . publish ( lang ) if set_home : page . set_as_homepage ( ) return page . get_draft_object ( ) | Create a single page or titles | 222 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.